【发布时间】:2011-09-08 22:18:16
【问题描述】:
我很难解决这个问题,因为我找到了答案,但它不起作用。我有一个带有 SelectMultiple/CheckboxSelectMultiple 字段的表单的 Django 应用程序......
我的目标
我需要在模板中迭代我的“标签”字段的选项。
在模板中打印{{ form.labels }} 可以正常工作(也就是说,该对象可以正常到达那里)。
我的问题
我在整个网络上都找到了相同的方法来做到这一点 - 我尝试了我能想到的所有变体。例如,请参阅 @Jarret Hardie 的回答 here。
我的代码
模型.py
class myModle(models.Model):
labels = models.CharField(max_length=1000)
class Meta:
db_table = u'myTable'
forms.py
class MYMODELForm(ModelForm):
class Meta:
model = myModel
def __init__(self, *args, **kwargs):
super(MYMODELForm, self).__init__(*args, **kwargs)
labelList = set()
#now I'm filling the set with strings (label names)
#one of the two following line:
self.fields['labels'] = forms.CharField(required=False,widget=forms.CheckboxSelectMultiple(choices=[(x,x) for x in labelList]))
self.fields['labels'] = forms.CharField(required=False,widget=forms.SelectMultiple(choices=[(x,x) for x in labelList]))
myTemplate.html
<table>
<tr>
<td>
<!-- All variations of... -->
{% for choice_id, choice_label in form.labels.field.items %}
{{ choice_id }} = {{ choice_label }} <br/>
{% endfor %}
</td>
</tr>
</table>
myStyle.css
Nothing interesting her...
views.py
Nothing interesting her...
所以...
为什么哦为什么这不起作用???
【问题讨论】:
标签: django django-templates django-forms