LaVOZs

The World’s Largest Online Community for Developers

'; Django Form how to set field value after clean() - LavOzs.Com

I have a form that allow to select a point on a map or a postal code. The result will be a tuple longitude/latitude of the selected point or of the centroid of the postal code area. I want to keep the 2 input widget synchronized when re-displaying the formview.

Here you have the solution I've found thanks to what explained in 813418 but modifying the raw data of the form is not recomended, how can I implement such behaviour in a better manner?

class MyForm(geoforms.Form):

    postalcode = ModelChoiceField(
        queryset=PostalCode.objects.all(),
        required=False,
        initial=2429,
        widget = Select()
    )
    coordinates = geoforms.PointField(
        widget=CustomOSMWidget(),
        required=False,
        srid=4326,
        initial=Point(4.72, 50.63, srid=4326)
    )

    def __init__(self, *args, **kwargs):

        super(MyForm, self).__init__(*args, **kwargs)   
        return

    def clean(self):

        cl_data = super(MyForm, self).clean()

        if not cl_data.get("coordinates"):
            cl_data["coordinates"] = Point(
                float(cl_data["postalcode"].longitude),
                float(cl_data["postalcode"].latitude),
                srid=4326
            )
        else:
            nearest_zipcode = PostalCode.objects.get_nearest_postal_code_centroid(
                longitude=cl_data["coordinates"].x, latitude=cl_data["coordinates"].y)

            cl_data["postalcode"] = nearest_zipcode

        # to synchronize form fields
        # BEWARE changing the raw data of the form is not recomended
        self.data = self.data.copy()  # IMPORTANT, self.data is immutable
        self.data.update(postalcode=cl_data["postalcode"])
        self.data.update(coordinates=cl_data["coordinates"])

        return cl_data
Related
How to combine two or more querysets in a Django view?
Django - Set Up A Scheduled Job?
Django set default form values
Django set field value after a form is initialized
How to check Django version
Custom latitude/longitude form field in Django
Create empty queryset by default in django form fields
Initial value is not working for ChoiceField on django-filters