渲染多个表单实例 [英] Render multiple Form instances

查看:133
本文介绍了渲染多个表单实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的应用程序,用户应该对比赛结果进行打赌。比赛由两支球队组成,一个结果和一个股权。在Django管理员中创建与团队的匹配,参与者将填写结果和股份。



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



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



当我从django shell中执行此操作时,它的工作正常,但是当我加载视图时,这些实例不会呈现。



表单如下所示:

  class SuggestionForm(forms.Form):
def __init __(self ,* args,** kwargs):
try:
match = kwargs.pop('match')
除了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 ['shares'] = forms.IntegerField(label ='',required = True,max_value = 50,min_value = 10,initial = 10)

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

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

在匹配中匹配:
f =小号uggestionForm(request.POST或None,match = match)
form_collection ['match_%s'%match.id] = f

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

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



$%$ {$ {$} $ {$ {$} $ {$ {$} $ {$}
{%endfor%}

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



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



非常感谢您的建议。

解决方案

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

  {%for key,dictionary.items中的值%} {{value}} {%endfor%} 

因此

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

应该诀窍!



否则你可以把你的表单放在一个列表中,这将更有意义,如果你的主要目标是保留他们的订单,并拥有模板代码!


I have a simple application where users are supposed to bet on outcome of a match. A match consists of two teams, a result and a stake. Matches with teams are created in the Django admin, and participants are to fill in result and stake.

The form must be generated dynamically, based on the matches in the database.

My idea is to have one (Django) Form instance for each match and pass these instances to the template.

It works fine when I do it from django shell, but the instances aren't rendered when I load my view.

The form looks like this:

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)

My (preliminary) view looks like this:

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

My initial thought was that I could pass the form_collection to the template and the loop throught the collection like this, but id does not work:

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

(The output is actually the dict keys with added spaces in between each letter - I've no idea why…)

It works if I only pass one Form instance to the template and only runs the inner loop.

Suggestions are greatly appreciated.

解决方案

To iterate over a dictionary in a django template you have to use:

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

therefore

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

should do the trick!

Otherwise you could put your forms in a list, which would make more sense if your main goal is to preserve their order and have the template code as it is!

这篇关于渲染多个表单实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆