Skip to content Skip to sidebar Skip to footer

Django Form - Type Of Variable Changes When Reloaded After Validation Error

I have spent some time on this but cannot figure out the exact cause of the following behaviour. I have a Django form and in the template I am trying to see if an integer is presen

Solution 1:

After the user submitted the form, {{ form.area.value }} (which in Python resolves to form["area"].value) is populated with the raw data from request.POST, which are indeed strings.

You didn't clearly explain what kind of "fancy thing" you're trying to do in the template so it's hard to come with a "best" solution for your use case, but as a general rule, templates are not the place for anything fancy - that's what Python is for (either in your view, in your form, in a custom templatetag or filter etc).

A very quick and simple solution would be to add a method to your form that returns the area boundfield values as ints:

class SchoolForm(forms.ModelForm):
    # your code here

    def area_values(self):
        # XXX this might require some conditionals or
        # error handling to be failsafe 
        # works with both python 2.x and 3.x
        return [int(v) for v in self["area"].value()]

then in your template, replace {% if pk in form.area.value %} with {% if pk in form.area_values %}


Post a Comment for "Django Form - Type Of Variable Changes When Reloaded After Validation Error"