Latitude/longitude widget for pointfield?

前端 未结 5 1485
灰色年华
灰色年华 2020-12-16 00:39

Is there a widget for PointField as separate latitude/longitude inputs? Like SplitDateTimeWidget for DateTimeField.

5条回答
  •  不思量自难忘°
    2020-12-16 01:21

    @Ramast, approaches the same issue in a more pythonic way. I have incorporated the changes to my code, it feels great to always improve.


    This is how I managed -at last- to keep separate fields for lattitude and longitude without having to save them in the database since the values are already saved in the PointField.

    The idea is :

    • If we are inserting a new entry, the latitude and longitude fields will be used to set the PointField
    • If we open an existing PointField entry, it will be used to provide the latitude and longitude values in the relevant FormFields.

    models.py

    from django.contrib.gis.db import models as geomodels
    
    
    class Entry(geomodels.Model):
        point = geomodels.PointField(
            srid=4326,
            blank=True,
            )
    

    admin.py

    from myapp.forms import EntryForm
    from django.contrib import admin
    
    
    class EntryAdmin(admin.ModelAdmin):
        form = EntryForm
    
    
    admin.site.register(Entry, EntryAdmin)
    

    forms.py

    from django import forms
    from myapp.models import Entry
    from django.contrib.gis.geos import Point
    
    
    class MarketEntryForm(forms.ModelForm):
    
        latitude = forms.FloatField(
            min_value=-90,
            max_value=90,
            required=True,
        )
        longitude = forms.FloatField(
            min_value=-180,
            max_value=180,
            required=True,
        )
    
        class Meta(object):
            model = MarketEntry
            exclude = []
            widgets = {'point': forms.HiddenInput()}
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            coordinates = self.initial.get('point', None)
            if isinstance(coordinates, Point):
                self.initial['longitude'], self.initial['latitude'] = coordinates.tuple
    
        def clean(self):
            data = super().clean()
            latitude = data.get('latitude')
            longitude = data.get('longitude')
            point = data.get('point')
            if latitude and longitude and not point:
                data['point'] = Point(longitude, latitude)
            return data
    

提交回复
热议问题