views:

153

answers:

1

Hello I am currently working on a django project, in one of my Models I have a file upload and image upload, with the parameters of these two fields both are set to blank=True, however there is a stipulatation with this and it is that field can only be blank if one of the two is not, so for example, if the imagefield is complete then the user does not have to upload a file, and if the filefield is complete then user does not need to upload an image.

My problem is I am struggling to figure out the logic, this is within the admin section so I understand I will have the overwrite the clean data. Can anyone help?

+3  A: 

You just need to define a custom clean() method on the ModelForm that checks if one or both of the fields is populated.

def clean(self):
    file_field = self.cleaned_data.get('file_field')
    image_field = self.cleaned_data.get('image_field')

    if file_field and image_field:
        raise forms.ValidationError("You should only provide one of File or Image")
    elif not file_field and not image_field:
        raise forms.ValidationError("You must provide either File or Image")

    return self.cleaned_data
Daniel Roseman
Thanks, though I think I missed out, that both a file and an image can be uploaded together, i assume this will change the condition some what?
sico87
Sure, then just drop the first `if`.
Daniel Roseman