有条件地需要Django表单字段 [英] Django form field required conditionally

查看:87
本文介绍了有条件地需要Django表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要有条件地设置一个布尔值为True或False的字段。如果is_company设置为True?

  class SignupFormExtra(SignupForm):
is_company = fields.BooleanField(label = u是公司?),
required = False)
NIP = forms.PLNIPField(label =(u'NIP'),required = False)


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


解决方案

查看有关清洁的章节并验证文档中相互依赖的字段



文档中给出的示例可以轻松适应您的方案:

  def clean(self):
cleaning_data = super(SignupFormExtra,self).clean()
is_company = clean_data.get (is_company)
nip = clean_data.get(NIP)
如果is_company而不是nip:
raise forms.ValidationError(NIP是必填字段)
return clean_data


I'd like to have a field which is required conditionally based on setting a boolean value to True or False.

What should I return to set required =True if is_company is set to 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

解决方案

Check the Chapter on Cleaning and validating fields that depend on each other in the documentation.

The example given in the documentation can be easily adapted to your scenario:

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

这篇关于有条件地需要Django表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆