How do you make django form validation dynamic?

前端 未结 4 1882
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 21:53

I have a form that needs to have either a valid url or a valid file for uploading:

class ResourceUpload(ModelForm):
   ...        
   uploadedfile = forms.Fi         


        
4条回答
  •  暖寄归人
    2021-01-13 22:42

    Here's my solution which really works... (tested)

    def __init__(self, *args, **kwargs):
        super(YourForm, self).__init__(*args, **kwargs)
    
        if self.data and self.data.get('field_name') != 'SOMETHING':
            self.fields.get('field_name2').required = True
    

    This makes field_name2 a required field if field_name's input was not 'SOMETHING'. Django rocks!

提交回复
热议问题