Opened 6 years ago

Closed 6 years ago

#18554 closed Uncategorized (worksforme)

Template rendering based on value of hidden BooleanFields

Reported by: David Owned by: nobody
Component: Forms Version: 1.3
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I'm not sure if this is a bug or not, but it's caused me quite a headache so I thought I'd report it.

It comes down to wanting to make decisions in the template based on the value of a Boolean HiddenInput field. Essentially you have to use strings instead of Boolean values to get it working, which doesn't seem right.

Here's the code:

The form:

class TestForm(forms.Form):
    text1 = forms.CharField()
    text2 = forms.CharField()
    bool1 = forms.BooleanField(required=False, widget=forms.HiddenInput)

The view:

def testview(request):
    if request.method == 'POST':
        form = TestForm(request.POST)
        form = TestForm(initial={'bool1':True})
    return render_to_response('test_form.html', {'form': form})

The template:

<form method='post' action=''>
  {{ form }}
  {{ form.bool1.value|yesno }}

What I would expect to happen is to be able to use the yesno filter (or at the very least the 'if' tag) to test if the value in the boolean field is True or False. This doesn't work though, if the other fields fail to validate and the form is resubmitted.

In the end I had to make the following changes. I can understand the first (since maybe initial should just be all strings?) but the ifequal method in the template seems clumsy:

#Pass the initial value as a string
form = TestForm(initial={'bool1':'True'})
{% ifequal form.bool1.value 'True' %}yes{% else %}no{% endifequal %}

Change History (1)

comment:1 Changed 6 years ago by Aymeric Augustin

Resolution: worksforme
Status: newclosed

I can't reproduce this in current master.

The following three alternatives all return the expected result:

{{ form.bool1.value }}
{{ form.bool1.value|yesno }}
{% if form.bool1.value %}Yes{% else %}No{% endif %}

The problem may have been fixed after Django 1.3.

Note: See TracTickets for help on using tickets.
Back to Top