2016-07-15 86 views
0

我試圖在Django上的模板中顯示ChoiceField,但我無法使其工作。無法在Django中的模板上呈現ChoiceField

我在這裏找到了一些解決方案,但似乎不適用於我(Possible solution),但我得到錯誤:too many values to unpack在線{{ form.as_p }}

因此,在網上搜索,我發現這Solution,但我無法添加適應我的代碼,並使其工作。我得到一個TextField而不是一個「Dropdown」(在Django Choicefield中)。此外,這個解決方案列出了for循環中的所有項目,我得到4個文本字段,而是2個選擇字段與元素。

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並訪問元素?我做錯了什麼?

謝謝。

+0

在'forms.py'中,'forms.ChoiceField'是通過'choices'參數調用的,它是一個字符串而不是元組。你可以嘗試替換嗎? – raphv

+0

你可以使'input type =「choicefield」',只有'radio'或'checkbox' – valignatev

+0

ChoiceFields是複雜的領域,你也可能想把它們渲染爲'