4

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..

1 Answer 1

5

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 %}
Sign up to request clarification or add additional context in comments.

2 Comments

that seems to work for fields that aren't being altered in anyway in the form...so that answer is kinda correct, please see my edit.
Please note that this is an old answer. Nowadays you can do: {% if form.field.value == 'whatever' %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.