How do I display the value of a Django form field in a template?
Solution 1:
This was a feature request that got fixed in Django 1.3.
Here's the bug: https://code.djangoproject.com/ticket/10427
Basically, if you're running something after 1.3, in Django templates you can do:
{{ form.field.value|default_if_none:"" }}
Or in Jinja2:
{{ form.field.value()|default("") }}
Note that field.value()
is a method, but in Django templates ()
's are omitted, while in Jinja2 method calls are explicit.
If you want to know what version of Django you're running, it will tell you when you do the runserver command.
If you are on something prior to 1.3, you can probably use the fix posted in the above bug: https://code.djangoproject.com/ticket/10427#comment:24
Solution 2:
You can do this from the template with something like this:
{% if form.instance.some_field %}
{{form.instance.some_field}}
{% else %}
{{form.data.some_field}}
{% endif %}
This will display the instance value (if the form is created with an instance, you can use initial instead if you like), or else display the POST data such as when a validation error occurs.