Ted
Ted

Reputation: 12318

Django Template Tag to get specific form field

I have a survey application that creates forms of dynamic size. I use the formula "question_id_part" where question is fixed, id is the id of the question being asked, and part is one of three parts.

In my template, I need to be able to group these by a category, so I loop through the categories in the survey, get all the questions in that category, then I have a template tag to get my form field.

{% load my_tags %}
...
{% for category in survey.category_set.all %}
    <h3>{{category}}</h3>
    {% for question in category.factor_set.all %}
        {% get_field_for_question_part question.id form "type" %} 
    {% endfor %}
{% endfor %}
...

Then I have a corresponding template tag that looks like this:

@register.simple_tag
def get_field_for_question_part(question_id, form, part):
    field_name = "question_%s_%s" % (question_id, part)
    field = form.fields[field_name]
    return BoundField(form, field, field_name)

My question is this: By explicitly importing BoundField my template tag knows too much about how forms work internally and thus is brittle to future changes in the non-public behavior of forms. Thus, it seems to me that the BoundField should be accessible somehow as a method on field -- but for the life of me I can't figure out what that method would be. Am I missing something obvious?

Upvotes: 2

Views: 1643

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239240

Try:

@register.simple_tag
def get_field_for_question_part(question_id, form, part):
    field_name = "question_%s_%s" % (question_id, part)
    return form.__getitem__(field_name)

See method definition on line 101 here: django/forms/forms.py

Upvotes: 2

Related Questions