0

Fairly new to Django here, so I don't know if I'm just not getting it or this is a bug. Let's say I have a form class:

class SurveyTwo(forms.Form):  
  food = [forms.BooleanField(required=False, initial=False, label="Seafood")]

Then, in the corresponding template, I am trying to access this by typing

{{ form.food.0 }}

When I do this, I get on my page:

<django.forms.fields.BooleanField object at 0x1c5b990>

Not the "Seafood" checkbox I was looking for. I can access the label just fine by doing {{ form.food.0.label }} but the checkbox just appears as that string. Should I be able to do this or not?

Essentially what I am trying to do is to pass an array of checkboxes to my form template, rather than having to define each form variable/field. I want to do this because I'm going to have a large number of checkboxes and want to be able to lay them out in a certain order (with a 2D array), rather than define them and lay them all out manually. If I can't do the above, does anyone know of a simpler solution? Thanks.

Mark

2
  • Is it a django thing that you don't say {{ forms.field[0] }} Commented Dec 15, 2010 at 21:54
  • Yeah in the templates (at least to my understanding), you have to access an array with a ., ie .0, .1, .2. Like I said, {{ form.food.0.label }} will output "Seafood". Commented Dec 15, 2010 at 22:29

1 Answer 1

1

You can register simple template tag:

from django import template
register = template.Library()

@register.simple_tag
def bound_field(form, name):
    """ returns bound field """
    return form.__getitem__(name)

Then in template you just use:

{% bound_field form <field_name> %}

where is name of field. If you have dynamicly generated fields that names you don't know you can access to them via fields.keys in this case generating all fields will look like

{% for name in form.fields.keys %}
    {% bound_field form name %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

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.