Django表单不显示特定输入

时间:2010-07-23 00:36:15

标签: python django forms

说,我有一个这样的模型:

class Fleet(models.Model):
    user = models.ForeignKey(User)
    [...]
    ship1 = models.IntegerField(default=0)
    ship2 = models.IntegerField(default=0)
    ship3 = models.IntegerField(default=0)
    ship4 = models.IntegerField(default=0)

表格:

class sendFleet(forms.Form):
    [...]
    ship1 = forms.IntegerField(initial=0)
    ship2 = forms.IntegerField(initial=0)
    ship3 = forms.IntegerField(initial=0)
    ship4 = forms.IntegerField(initial=0)

如果用户没有'船只'可用(如Fleet模型中的= 0),如何隐藏表格中的字段?

2 个答案:

答案 0 :(得分:2)

您可以覆盖表单中的visible_fields(或hidden_fields,如果您确实需要隐藏字段)方法,将其标记为“不可见”(或隐藏的输入)。有关详细信息,请参阅docs

编辑:这样的事情应该有用......

class sendFleet(forms.Form):
    [...]
    ship1 = forms.IntegerField(initial=0)
    ship2 = forms.IntegerField(initial=0)

    def visible_fields(self):
        # create a list of fields you don't want to display
        invisibles = []
        if self.instance.ship1 == 0:
            invisibles.append(self.fields['ship1'])

        # remove fields from the list of visible fields
        visibles = super(MailForm, self).visible_fields()
        return [v for v in visibles if v.field not in invisibles]

然后在你的模板中:

{% for field in form.visible_fields %}
    {{ field.label_tag }} : {{ field }}
{% endfor %}

答案 1 :(得分:1)

似乎这个问题可以通过使用从Fleet到Ship的ManyToManyField,或者从Ship到Form的ForeignKey,然后只是表单中的ModelMultipleChoiceField来更好地解决......但也许我有点'我不理解。

无论哪种方式,MultipleChoiceField都可能比这组IntegerField更好。这基本上就是MultipleChoiceField的用途。