Search code examples
djangodjango-admingeodjangodjango-leaflet

Django Leaflet: Add form fields for latitude and longitude


I am using the django-leaflet package to display the map in the django admin for a PointField. However, I wanted to put fields so that it would be possible to write the latitude and longitude, as an alternative to selecting the point on the map.

How can I add these fields to the form?

Note: the Django Map Widgets package has the ability to insert coordinates, but I don't want to use it because it requires a key.


Solution

  • You can create a model form with 2 new fields such as lat, lng. Then you can validate if point selected in the map or lat, lng fields are filled.

    class PointEntryOrSelectForm(forms.ModelForm):
        lat = forms.FloatField(required=False, label='Latitude')
        lng = forms.FloatField(required=False, label='Longtitude')
    
        class Meta:
            widgets = {'geom': LeafletWidget()}
            model = YourModel
            exclude = ['', ]
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            geom = self.initial.get("geom", None)
            if isinstance(geom, Point):
                self.initial["lng"], self.initial["lat"] = geom.tuple
    
        def clean(self):
            data = super().clean()
            if set(self.changed_data)>={"lat","lng"}:
                lat, lng = data.pop("lat", None), data.pop("lng", None)
                data["geom"] = Point(lng, lat, srid=4326)
        
            if not (data["geom"] or (data["lat"] and data["lng"])):
                raise forms.ValidationError(
                    {"geom": "No coordinates."})
            return data
    
    @admin.register(YourModel)
    class YourModelAdmin( LeafletGeoAdmin):
        form = PointEntryOrSelectForm