1

I want to know if there's a way to know when the OSMWidget coordinates have been changed, I'm pretending to reflect this change on the Longitude and Latitude fields. I have the following form:

from django.contrib.gis import forms
from .models import Branch


class BranchCreateForm(forms.Form):
    name = forms.CharField(label ="Name", max_length=120)
    image_facade = forms.ImageField( label="Image Facade")
    longitude = forms.DecimalField(label = "Latitude", max_digits=9, decimal_places=6)
    latitude = forms.DecimalField(label = "Longitude", max_digits=9, decimal_places=6)
    location = forms.PointField(
        widget=forms.OSMWidget(
            attrs={'map_width': 600,
                   'map_height': 400,
                   'template_name': 'gis/openlayers-osm.html',
                   'default_lat': 42.1710962,
                   'default_lon': 18.8062112,
                   'default_zoom': 6}))

1 Answers1

1

A PointField contains the longitude and latitude coordinates of the Point object that it creates. Therefore you don't need to save them separately as DecimalFields.

Whenever a change is made through the widget and the form is saved, the Point is updated accordingly.

Let's assume that you have a Branch instance then you can access the coordinates as follows:

br = Branch.objects.get(pk=1)
longitude = br.location.x
latitude = br.location.y

EDIT After declaration Provided by OP:

You don't need to add the fields in the form class.
What you need is to access the specific form fields in the template:

{{ form.location.x|default_if_none:"" }}
{{ form.location.y|default_if_none:"" }}

Source: Display value of a django form field in a template?

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
  • 1
    The model doesn't have the longitude and latitude fields, I'm just using them in the template, its just for visualization purposes, for example if a user is creating a new branch, and uses the map to change the default point, I want this to be reflected on the latitude and longitude input fields. – katbarahona Mar 29 '19 at 16:40
  • @katbarahona I have updated my answer, does this fit your needs? – John Moutafis Apr 01 '19 at 15:31