本文介绍了如何使django表单验证动态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表单需要有一个有效的URL或一个有效的文件进行上传:
I have a form that needs to have either a valid url or a valid file for uploading:
class ResourceUpload(ModelForm):
...
uploadedfile = forms.FileField('file')
url_address = forms.URLField('url')
...
如何覆盖 FileField
和 URLField
验证器,以便Django只会在上述两个字段都无效时引发错误,但除非另有一个无效,否则只有另一个有效?
How can I override the FileField
and URLField
validators so that Django only raises an error if both of the fields above are invalid but excepts one being invalid so long as the other is valid?
推荐答案
我的解决方案
专业人士:它保留星号的真正需要的字段和默认错误消息
my solution
pros: it keeps the asterisk for the really required field and default error messages
class Form(forms.ModelForm):
field1 = SelectField
field2 = ...
field3 = ...
def __init__(self, *args, **kwargs):
super(Form, self).__init__(*args, **kwargs)
if kwargs['data']:
if kwargs['data'].get('field1') == '1':
self.fields['field2'].required = True
self.fields['field3'].required = False
elif kwargs['data'].get('field1') == '2':
self.fields['field2'].required = False
self.fields['field3'].required = True
这篇关于如何使django表单验证动态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!