Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display the value of a Django form field in a template?

I have a form with an email property.

When using {{ form.email }} in case of some validation error, Django still renders the previous value in the input tag's value attribute:

<input type="text" id="id_email" maxlength="75" class="required"        value="[email protected]" name="email"> 

I want to render the input tag myself (to add some JavaScript code and an error class in case of an error). For example this is my template instead of {{ form.email }}:

<input type="text" autocomplete="on" id="id_email" name="email"        class="email {% if form.email.errors %} error {% endif %}"> 

However, this does not display the erroneous value ([email protected] in this example) to the user.

How do I get the field's value in the template?

like image 993
Eran Kampf Avatar asked Feb 10 '10 12:02

Eran Kampf


People also ask

How do I get field value in Django?

To get value from form field with Python Django, we can use the form's cleaned_data property. to use the myform. cleaned_data property to get the form values as a dict.

How do you receive data from a Django form with a post request?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.


1 Answers

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

like image 177
mlissner Avatar answered Sep 22 '22 00:09

mlissner