Django 模板标签获取特定表单字段
我有一个调查应用程序,可以创建动态大小的表单。我使用公式“question_id_part”,其中问题是固定的,id 是所问问题的 id,part 是三个部分之一。
在我的模板中,我需要能够按类别对这些进行分组,因此我循环访问调查中的类别,获取该类别中的所有问题,然后我有一个模板标记来获取我的表单字段。
{% 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 %}
...
然后我有一个相应的模板标签,如下所示:
@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)
我的问题是这样的: 通过显式导入 BoundField,我的模板标记对表单内部的工作方式了解太多,因此对于表单非公开行为的未来变化很脆弱。因此,在我看来,BoundField 应该可以作为现场方法以某种方式进行访问——但我一生都无法弄清楚该方法是什么。我错过了一些明显的东西吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
请参阅第 101 行的方法定义: django/forms/forms.py
Try:
See method definition on line 101 here: django/forms/forms.py