【问题标题】:Django form field required conditionally有条件地需要 Django 表单字段
【发布时间】:2012-06-13 14:56:42
【问题描述】:

我希望有一个基于将布尔值设置为TrueFalse 的有条件需要的字段。

如果is_company 设置为True,我应该返回什么设置required =True

class SignupFormExtra(SignupForm):
    is_company = fields.BooleanField(label=(u"Is company?"), 
                                     required=False)
    NIP = forms.PLNIPField(label=(u'NIP'), required=False)

    def clean(self):
        if self.cleaned_data.get('is_company', True):
            return ...?
        else:
            pass

【问题讨论】:

    标签: django forms


    【解决方案1】:

    查看文档中关于Cleaning and validating fields that depend on each other 的章节。

    文档中给出的示例可以很容易地适应您的场景:

    def clean(self):
        cleaned_data = super(SignupFormExtra, self).clean()
        is_company = cleaned_data.get("is_company")
        nip = cleaned_data.get("NIP")
        if is_company and not nip:
            raise forms.ValidationError("NIP is a required field.")
        return cleaned_data
    

    【讨论】:

    • @arie 提供的链接还介绍了如何通过将 raise 语句替换为 self._errors["NIP"] = self.error_class(["This is an required field. "])
    • @Seth 感谢您的评论!这真的很有帮助!
    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多