Ben Kilah
Ben Kilah

Reputation: 3475

Form field value in django template

Quick question,

I am able to output the value of a form field using

{{ form.field.value }}

But I cannot seem to check that value in an if statement.

{% if form.field.value == 'whatever' %}

Always fails.. any ideas?

The field is a boolean type field.

EDIT - the answer given below works for some fields.. Here is what i'm trying to do;

Form field is a boolen field in a model, using this code in the form;

self.fields['information_request'] = forms.TypedChoiceField(choices=((True, 'Yes'), (False, 'No')), widget=forms.RadioSelect, coerce=lambda x: x and (x.lower() != 'false'))

The output is correct (eg. True or False) when using {{form.information_request.value}} - but when I use it in an IF statement in the template - it never works..

Upvotes: 4

Views: 9676

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169494

https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#if

The {% if %} tag evaluates a variable, and if that variable is "true" (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:

E.g.:

{% if form.field.value %}
    ...
{% endif %}

To test for falsiness:

{% if not form.field.value %}
    ...
{% endif %}

Upvotes: 5

Related Questions