无法在Django中的模板上呈现ChoiceField

时间:2016-07-15 10:03:38

标签: python django django-forms choicefield

我正在尝试在Django的模板中显示ChoiceField,但我无法使它工作。

我在这里找到了一些解决方案,但似乎对我不起作用(Possible solution),但我在第too many values to unpack行收到了错误:{{ form.as_p }}

所以在网上搜索,我发现了这个Solution,但是我无法添加到我的代码中并使其有效。我得到一个TextField而不是“Dropdown”(在Django Choicefield中)。而且,这个解决方案列出了for循环中的所有项目,我获得了4个文本字段,而不是2个包含元素的Choicefields。

我的forms.py看起来像是:

class SimpleDeploy(forms.Form):
    def __init__(self, networkList, policiesList, *args, **kwargs):
        super(SimpleDeploy, self).__init__(*args, **kwargs)
        if networkList and policiesList:
            self.fields['networkPartitions'] = forms.ChoiceField(choices=networkList)
            self.fields['applicationPolicies'] = forms.ChoiceField(choices=policiesList)
        else:
            self.fields['networkPartitions'] = forms.ChoiceField(choices='No network partitions found')
            self.fields['applicationPolicies'] = forms.ChoiceField(choices='No application policies found')

views.py上:

def simpleDeploy(request):
    netList = getDetailsNetworkPartitions(request)
    polList = getDetailsApplicationPolicies(request)
    if request.method == 'POST':
        abs(5) #Nothing here by the moment
    else:
        simpleForm = SimpleDeploy(networkList=netList, policiesList=polList)
    return render(request, 'apacheStratos/simpleDeploy.html', {'form': simpleForm})

其中netListpolList是元组列表,如:

[(u'application-policy-2', u'application-policy-2'), (u'application-policy-1', u'application-policy-1')]

在我的模板上,我试图将ChoiceField显示为:

<table class="table">
    {% for item in form.networkPartitions.field.choices %}
        <label for="">Network Partitions</label> <input type="choicefield" name="networkPartitions" value="{{item.1}}"/>
    {% endfor %}
    {% for item in form.applicationPolicies.field.choices %}
        <label for="">Application Policies</label> <input type="choicefield" name="applicationPolicies" value="{{item.1}}"/>
    {% endfor %}
</table>

如何在不使用for循环的情况下获取choicefield和访问元素?我做错了什么?

感谢。

1 个答案:

答案 0 :(得分:0)

感谢@raphv,解决方案是{{form.networkPartitions}}{{form.applicationPolicies}}放在模板上。这么简单....