开发者

How do I create a Django ModelForm, so that it's fields are sometimes required, sometimes not?

开发者 https://www.devze.com 2023-01-02 08:18 出处:网络
Ok, here is the question. Imagine I have a ModelForm which have only two fields. like this one: class ColorForm(forms.Form):

Ok, here is the question. Imagine I have a ModelForm which have only two fields. like this one:

class ColorForm(forms.Form):
    color_by_name = forms.CharField()
    color = forms.IntegerField(widget = forms.Select(choices=COLOR_CHOICES))

So a user can either input a color 开发者_Python百科name, a choose it from a list. Color is required, but that doesn't mean, that user should enter it manually. There do I put validation, so that my code checks if user selected color in dropdownlist and if not then he should write it manually?


Make them both required=False, but write a clean() method which checks for one or the other. See the validation documentation for an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消