【问题标题】:Render multiple Form instances渲染多个 Form 实例
【发布时间】:2011-02-26 12:46:47
【问题描述】:

我有一个简单的应用程序,用户应该在其中下注比赛的结果。一场比赛由两支球队组成,一个结果和一个赌注。与团队的比赛是在 Django 管理中创建的,参与者需要填写结果和赌注。

必须根据数据库中的匹配项动态生成表单。

我的想法是为每个匹配项创建一个 (Django) Form 实例,并将这些实例传递给模板。

当我从 django shell 执行此操作时,它工作正常,但是当我加载视图时实例未呈现。

表格如下所示:

class SuggestionForm(forms.Form):
    def __init__(self, *args, **kwargs):
        try:
            match = kwargs.pop('match')
        except KeyError:
            pass
        super(SuggestionForm, self).__init__(*args, **kwargs)
        label = match
        self.fields['result'] = forms.ChoiceField(label=label, required=True, choices=CHOICES, widget=forms.RadioSelect())
        self.fields['stake'] = forms.IntegerField(label='', required=True, max_value=50, min_value=10, initial=10)

我的(初步)视图如下所示:

def suggestion_form(request):
    matches = Match.objects.all()
    form_collection = {}

    for match in matches:
        f = SuggestionForm(request.POST or None, match=match)
        form_collection['match_%s' % match.id] = f

    return render_to_response('app/suggestion_form.html', {
        'forms': form_collection,
        },
        context_instance = RequestContext(request)
        )

我最初的想法是我可以将 form_collection 传递给模板并像这样循环遍历集合,但 id 不起作用:

        {% for form in forms %}
            {% for field in form %}
                {{ field }}
            {% endfor %}
        {% endfor %}

(输出实际上是每个字母之间添加空格的 dict 键 - 我不知道为什么......)

如果我只将一个 Form 实例传递给模板并且只运行内部循环,它就可以工作。

非常感谢您的建议。

【问题讨论】:

    标签: django forms django-forms


    【解决方案1】:

    再次强调,在一个页面上拥有多个表单的最佳方式是使用formsets

    【讨论】:

      【解决方案2】:

      要在 django 模板中遍历字典,您必须使用:

      {% for key,value in dictionary.items %}{{ value }}{% endfor %}
      

      因此

       {% for key, value in forms.items %}
          {% for field in value %}
              {{ field }}
          {% endfor %}
       {% endfor %}
      

      应该做的伎俩!

      否则,您可以将表单放在一个列表中,如果您的主要目标是保持其顺序并保持模板代码不变,这将更有意义!

      【讨论】:

      • 谢谢,成功了!我同意将表单实例放在列表中是一个更好的主意。
      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2022-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2017-08-07
      相关资源
      最近更新 更多