Django Templates: Two Ways to Access Form Data

If it's a forms.ModelForm, and you instantiated it by passing an instance, you can access it like this:

{{ person_form.instance.last_name }}

If the form is bound (i.e. form.is_bound is true) then you can access
its data attribute, which contains the data entered into the form.

If the form is valid (i.e. form.is_valid() is true), then you can
access the cleaned_data attributes as well.

So for example if you have form like this:

f = MyForm({ "last_name": "some_value"})

you can access the value in template in this way

{{ f.data.last_name }}

or alternatively, if your form is valid you can use:

{{ f.cleaned_data.last_name }}

The cleaned_data result might be different, however, due to some processing in the validation methods.

0 Comments, 0 trackbacks (Trackback URL)

0 responses to Django Templates: Two Ways to Access Form Data

Leave a Comment
  1. (required)
  2. Ignore this field:
  3. Don't put anything in this field:
    Don't put anything here:
  4. Leave this empty:
    (required)
  5. Your email is not publically displayed.