tags:

views:

46

answers:

2

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') 
   ...

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?

+4  A: 

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          
Dominic Rodger
A: 

Many thanks for the answer Dominic.

sithbunny
Use the comments section. I won't down-vote you since you are new.
the_drow