开发者

Django Template Tag to get specific form field

I have a survey application that creates forms 开发者_Go百科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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜