How do you make django form validation dynamic?

前端 未结 4 1879
佛祖请我去吃肉
佛祖请我去吃肉 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:47

    You'll need to set them both as required=False, so the database backend doesn't need them both filled in, and then use form cleaning:

    import forms
    
    class ResourceUpload(ModelForm):
       ...        
       uploadedfile = forms.FileField(required = False, upload_to='put/files/here')
       url_address = forms.URLField(required = False) 
       ...
    
       def clean(self):
           cleaned_data = self.cleaned_data
           uploadedfile = cleaned_data.get("uploadedfile ")
           url_address = cleaned_data.get("url_address ")
    
           if not uploadedfile and mot url_address :
               raise forms.ValidationError("Provide a valid file or a valid URL.")
    
           return cleaned_data          
    

提交回复
热议问题