【问题标题】:django problem iterating over SelectMultiple/CheckboxSelectMultiple in template在模板中迭代 SelectMultiple/CheckboxSelectMultiple 的 django 问题
【发布时间】: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


    【解决方案1】:

    您使用的是items 而不是choices。

    当前:

    {% for choice_id, choice_label in form.labels.field.items %}

    应该是:

    {% for choice_id, choice_label in form.labels.field.choices %}

    由于您已将选项放在小部件上,因此这些选项会覆盖字段的选择,因此请迭代小部件选项:

    {% for choice_id, choice_label in form.labels.field.widget.choices %}

    【讨论】:

    • 它不起作用(我实际上是从这个开始的)。 HTML 页面在这部分没有显示任何内容 - 这是个大问题。
    • 又看了一下代码。您已经在小部件上设置了选项,而不是在字段上(小部件选项在渲染时会覆盖字段选项)。所以尝试迭代form.labels.field.widget.choices。
    • 以及如何检查选项是否被选中?
    • 从字段值中获取。
    猜你喜欢
    • 2023-03-16
    • 2012-12-03
    • 2014-12-19
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多