Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## [0.13.1] - 2024-03-02
- Added: Inline form support

## [0.13.0] - 2022-03-22
- Added: Django 4.0 support
- Added: Python 3.10 support
Expand Down
51 changes: 50 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,55 @@ USAGE:
},
}

USING INLINE FORMS:
===================
- To use as a model admin inline form, everything is basically the same as above except for the widget
used. It's best to use ``django.contrib.admin.StackedInline`` as opposed to ``django.contrib.admin.TabularInline``

.. code:: python

from django.db import models
from django_google_maps import fields as map_fields

class Shipment(models.Model):
tracking_id = models.CharField(max_length=255)
carrier = models.CharField(max_length=255)

class Location(models.Model):
shipment = models.ForeignKey(Shipment)
address = map_fields.AddressField(max_length=200)
geolocation = map_fields.GeoLocationField(max_length=50)

- in the ``forms.py`` file, define the form and set widget for "address" field:

.. code:: python

from django import forms
from django_google_maps import widgets as map_widgets

class LocationForm(forms.ModelForm):
class Meta:
model = models.Location
widgets = {
"address": map_widgets.GoogleMapsAddressInlineWidget(),
}

- in the ``admin.py`` file, define a model form and a stacked inline like below:

.. code:: python

from django.contrib import admin

from . import models, forms

class LocationInline(admin.StackedInline):
model = models.Location
form = forms.LocationForm

@admin.register(models.Shipment)
class ShipmentAdmin(admin.ModelAdmin):
inlines = [LocationInline]

That should be all you need to get started.

I also like to make the geolocation field readonly in the admin so a user
Expand All @@ -101,4 +150,4 @@ I get around to it I'll see if I can create a method that will build that
into the model.

.. |Build Status| image:: https://travis-ci.org/madisona/django-google-maps.png
:target: https://travis-ci.org/madisona/django-google-maps
:target: https://travis-ci.org/madisona/django-google-maps
Empty file removed django_google_maps/models.py
Empty file.
Original file line number Diff line number Diff line change
@@ -1,11 +1,31 @@
@media (min-width: 848px) {
.map_canvas_wrapper {margin-left: 170px;}
.main.shifted .map_canvas_wrapper {margin-left: 0;}
.map_canvas_wrapper {
margin-left: 170px;
}

.main.shifted .map_canvas_wrapper {
margin-left: 0;
}
}

@media (min-width: 1118px) {
.main.shifted .map_canvas_wrapper {margin-left: 170px;}
.main.shifted .map_canvas_wrapper {
margin-left: 170px;
}
}

#id_address,
input[id^="id_locations-"][id$="-address"] {
width: 40em;
max-width: 100%;
}

#id_address {width: 40em;}
.map_canvas_wrapper {width: 100%;}
#map_canvas {width: 100%; height: 40em;}
.map_canvas_wrapper {
width: 100%;
}

#map_canvas,
[id^="locations-"][id$="-address_map_canvas"] {
width: 100%;
height: 30em;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
This script expects:

<input type="text" name="address" id="id_locations-{index}-address" />
<input type="text" name="geolocation" id="id_locations-{index}-geolocation" />
*/

class LocationFormGoogleMap {
constructor(index) {
this.index = index;
this.autocomplete = null;
this.geocoder = new google.maps.Geocoder();
this.map = null;
this.marker = null;
this.geolocationId = `id_locations-${index}-geolocation`;
this.addressId = `id_locations-${index}-address`;
this.mapCanvasId = `locations-${index}-address_map_canvas`;
}

initialize() {
let lat = 0;
let lng = 0;
let zoom = 2;

// Update zoom level and initial cordinates if form is bound
const existingLocation = this.getExistingLocation();
if (existingLocation) {
lat = existingLocation[0];
lng = existingLocation[1];
zoom = 12;
}

const latlng = new google.maps.LatLng(lat, lng);
const mapOptions = {
zoom: zoom,
center: latlng,
mapTypeId: this.getMapType(),
};
this.map = new google.maps.Map(document.getElementById(this.mapCanvasId), mapOptions);

if (existingLocation) this.setMarker(latlng);

this.autocomplete = new google.maps.places.Autocomplete(
document.getElementById(this.addressId),
this.getAutoCompleteOptions()
);

this.autocomplete.addListener("place_changed", () => this.codeAddress());

$(`#${this.addressId}`).keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
}

getMapType() {
const geolocationInput = document.getElementById(this.addressId);
const allowedType = ["roadmap", "satellite", "hybrid", "terrain"];
const mapType = geolocationInput.getAttribute("data-map-type");

if (mapType && -1 !== allowedType.indexOf(mapType)) return mapType;
return google.maps.MapTypeId.HYBRID;
}

getAutoCompleteOptions() {
const geolocationInput = document.getElementById(this.addressId);
const autocompleteOptions = geolocationInput.getAttribute(
"data-autocomplete-options"
);

if (!autocompleteOptions) return { types: ["geocode"] };
return JSON.parse(autocompleteOptions);
}

getExistingLocation() {
const geolocationInput = document.getElementById(this.geolocationId);
if (geolocationInput && geolocationInput.value) {
return geolocationInput.value.split(",");
}
}

codeAddress() {
const place = this.autocomplete.getPlace();

if (place.geometry !== undefined) {
this.updateWithCoordinates(place.geometry.location);
} else {
this.geocoder.geocode({ address: place.name }, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
const latlng = results[0].geometry.location;
this.updateWithCoordinates(latlng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}

updateWithCoordinates(latlng) {
this.map.setCenter(latlng);
this.map.setZoom(18);
this.setMarker(latlng);
this.updateGeolocation(latlng);
}

setMarker(latlng) {
this.marker
? this.updateMarker(latlng)
: this.addMarker({ latlng: latlng, draggable: true });
}

addMarker(Options) {
this.marker = new google.maps.Marker({
map: this.map,
position: Options.latlng,
});

const draggable = Options.draggable || false;
if (draggable) {
this.addMarkerDrag(this.marker);
}
}

addMarkerDrag(marker) {
marker.setDraggable(true);
google.maps.event.addListener(marker, "dragend", (new_location) => {
this.updateGeolocation(new_location.latLng);
});
}

updateMarker(latlng) {
this.marker.setPosition(latlng);
}

updateGeolocation(latlng) {
document.getElementById(this.geolocationId).value = latlng.lat() + "," + latlng.lng();
$(`#${this.geolocationId}`).trigger("change");
}
}

$(document).ready(function () {
const addressInputSelector = "input[id^='id_locations-'][id$='-address']:visible";

// Initialize existing location forms
$(addressInputSelector).each(function (index) {
new LocationFormGoogleMap(index).initialize();
});

// Listen and check for insertion of new location forms
$(document).bind("formset:added", function (e) {
const newAddressInput = $(e.target).find(addressInputSelector);

if (newAddressInput) {
const index = parseInt(newAddressInput.attr("id").match(/(?<=-)\d+(?=-)/)[0]);
new LocationFormGoogleMap(index).initialize();
}
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{% include "django/forms/widgets/text.html" %}
<div class="map_canvas_wrapper">
<div id="{{ widget.name }}_map_canvas"></div>
</div>
27 changes: 0 additions & 27 deletions django_google_maps/tests/test_widget.py

This file was deleted.

75 changes: 75 additions & 0 deletions django_google_maps/tests/test_widgets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from django import test
from django.conf import settings

from django_google_maps import widgets


class WidgetTests(test.TestCase):
def test_render_returns_with_value(self):
widget = widgets.GoogleMapsAddressWidget()
results = widget.render("name", "value", attrs={"a1": 1, "a2": 2})
expected = '<input a1="1" a2="2" name="name" type="text" value="value" />'
expected += '<div class="map_canvas_wrapper">'
expected += '<div id="map_canvas"></div></div>'
self.assertHTMLEqual(expected, results)

def test_render_returns_blank_for_value_when_none(self):
widget = widgets.GoogleMapsAddressWidget()
results = widget.render("name", None, attrs={"a1": 1, "a2": 2})
expected = '<input a1="1" a2="2" name="name" type="text" />'
expected += '<div class="map_canvas_wrapper">'
expected += '<div id="map_canvas"></div></div>'
self.assertHTMLEqual(expected, results)

def test_widgets_media_js(self):
widget = widgets.GoogleMapsAddressWidget()
google_maps_js = (
"https://maps.google.com/maps/api/js?key={}&libraries=places".format(
settings.GOOGLE_MAPS_API_KEY
)
)
admin_js = "django_google_maps/js/google-maps-admin.js"
self.assertEqual(google_maps_js, widget.Media().js[1])
self.assertEqual(admin_js, widget.Media().js[2])

def test_template_used(self):
widget = widgets.GoogleMapsAddressWidget()
self.assertEqual(
widget.template_name,
"django_google_maps/widgets/map_widget.html",
)


class InlineWidgetTests(test.TestCase):
def test_render_returns_with_value(self):
widget = widgets.GoogleMapsAddressInlineWidget()
results = widget.render("locations-0-address", "New York", attrs={"attr1": 1})
expected = '<input attr1="1" name="locations-0-address" type="text" value="New York" />'
expected += '<div class="map_canvas_wrapper"><div id="locations-0-address_map_canvas"></div></div>'
self.assertHTMLEqual(expected, results)

def test_render_returns_blank_for_value_when_none(self):
widget = widgets.GoogleMapsAddressInlineWidget()
results = widget.render("locations-1-address", None, attrs={"a1": 1, "a2": 2})
expected = '<input a1="1" a2="2" name="locations-1-address" type="text" />'
expected += '<div class="map_canvas_wrapper">'
expected += '<div id="locations-1-address_map_canvas"></div></div>'
self.assertHTMLEqual(expected, results)

def test_widgets_media_js(self):
widget = widgets.GoogleMapsAddressInlineWidget()
google_maps_js = (
"https://maps.google.com/maps/api/js?key={}&libraries=places".format(
settings.GOOGLE_MAPS_API_KEY
)
)
admin_js = "django_google_maps/js/google-maps-admin-inline.js"
self.assertEqual(google_maps_js, widget.Media().js[1])
self.assertEqual(admin_js, widget.Media().js[2])

def test_template_used(self):
widget = widgets.GoogleMapsAddressInlineWidget()
self.assertEqual(
widget.template_name,
"django_google_maps/widgets/map_widget_inline.html",
)
Loading