【问题标题】:How to set field required if depends this of choice of other field in the same form in Django?如果依赖于在 Django 中以相同形式选择其他字段,如何设置所需字段?
【发布时间】:2012-11-17 21:17:08
【问题描述】:

我正在寻找这项任务的最佳解决方案。我在 forms.py 中有简单的表单类:

class CategoriesForm(Form):
    RADIO_CHOICES = (
        ('c1', _("C1")),
        ('c2', _("C2")),
        ('c3', _("C3")),
        ('c4', _("C4")),
    )
    category = forms.ChoiceField(widget=forms.RadioSelect(),choices=RADIO_CHOICES)

    subcategory_c1 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c1", public=True), empty_label="", label = "hhh")
    subcategory_c2 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c2", public=True), empty_label="", label = "rrr")
    subcategory_c3 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c3", public=True), empty_label="", label = "aaa")
    subcategory_c4 = forms.ModelChoiceField(queryset=Category.objects.filter(type="c4", public=True), empty_label="", label = "eeee")

    def __init__(self, *args, **kwargs):
        super(CategoriesForm, self).__init__(*args, **kwargs)

        self.fields["subcategory_c1"].required = False
        self.fields["subcategory_c2"].required = False
        self.fields["subcategory_c3"].required = False
        self.fields["subcategory_c4"].required = False

这只是一些草稿。

表单的行为应该如下:当我从单选字段中选择C1类别时,应该需要subcategory_c1。当我将选择 C2 类别时,subcategory_c2 应该是必需的,选择其他子类别字段(C1、C3、C4)应该是可选的。我希望我的解释清楚。

模板中的表格草稿:

field category (RadioSelect: C1, C2, C3, C4) <<required>>
field subcategory_c1 (Select: ---, a,b,c,d) <<required only if user checked C1>>
field subcategory_c2 (Select: ---, a,b,c,d) <<required only if user checked C2>>
field subcategory_c3 (Select: ---, a,b,c,d) <<required only if user checked C3>>
field subcategory_c4 (Select: ---, a,b,c,d) <<required only if user checked C4>>

提前感谢您的帮助。

【问题讨论】:

  • 嗯,我很好奇为什么没有人回答,不可能做到这一点或那么容易......

标签: python django django-forms


【解决方案1】:

如果添加了新选择,您的解决方案需要做很多事情。

更简洁的方法是使subcategory 具有所有可能的选择的一个字段,并在客户端使用JavaScript 过滤它们。作为没有 js 的用户的后备方案,应该有所有可能的分类良好的选择。

此解决方案很有意义,因为您需要具有动态变化选择的字段 - 看起来像是为客户端魔术工作。 :)

【讨论】:

    猜你喜欢
    • 2020-08-07
    • 2016-06-18
    • 2022-01-14
    • 2014-08-17
    • 1970-01-01
    • 2013-08-26
    • 2016-03-10
    • 2014-07-09
    • 1970-01-01
    相关资源
    最近更新 更多