Django 模板标签获取特定表单字段

发布于 2024-11-09 10:50:04 字数 871 浏览 0 评论 0原文

我有一个调查应用程序,可以创建动态大小的表单。我使用公式“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看海 2024-11-16 10:50:04

尝试:

@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)

请参阅第 101 行的方法定义: django/forms/forms.py

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文