I have 3 models linked with a foreign key:
class Region(models.Model):
name = models.CharField(max_length=20)
class Zipcode(models.Model):
zipcode = models.IntegerField()
name = models.CharField(max_length=20)
region = models.ForeignKey(Region)
class Address(models.Model):
street = models.Charfield(max_length=40)
zipcode = models.ForeignKey(Zipcode)
region = models.ForeignKey(Region)
In a next step I made a form based on the model Address.
Now I would like to automatically fill in the region field when the user fills in the zipcode field.
I know it is possible to calculate the values in the back-end etc, but is it possible to complete the region field almost ‘real-time’ when the user selects the zipcode field? In a way that it also visible in the form for the user?
Thanks!
I think you’ll want some sort of ajax lookup for this. For example, javascript (I suggest jquery) would be set to do a ajax request whenever someone entered a zipcode. Perhaps if the zipcode textbox length is six, then the onChange event would request the url “/ajax/get_region/60604/” which would map to the view below and pass in the zipcode. The view might return a json response which would indicate the region for that zip code. Finally, in the javascript callback function could update the dialog box on your site to indicate the region.
My recommendation is that the region would not even need to be posted back to the webserver…. the ajax lookup here would only be used for display purposes and then it would be calculated again during the POST. But, then again, I don’t know if you want the user to be able to manually enter both the region and the zipcode.
views.py
Finally, if you do want the user to be able to edit both region and zipcode in the form, you’ll want to ensure that the region and the zipcode are always consistent and you may want to build a check in the form that the user submits. Also, if the user disables javascript, you’ll want to provide an error to the user if they select the wrong region. You could override the clean() method on the form that would also lookup the region from the zipcode. If it doesn’t match the region that was posted by the front-end form, it would return an error message.
forms.py
Note, these code examples, haven’t been tested, but hopefully get the idea across.
Hope this helps,
Joe