Derek
Derek

Reputation: 12388

Django models: requiring user to input either field, but not both or neither?

Say I have an Image model

class Image(...
    # store file info
    image = ImageField(...
    # store link info
    url = URLField(...
    # storing either image or url is okay
    # storing both is NOT okay
    # storing neither is NOT okay

I want the user to be able to upload an image file or submit an image url to link to. Is there a way for the model to require the user to have at least one of the two fields?

Upvotes: 1

Views: 691

Answers (3)

Rohan
Rohan

Reputation: 53366

You have following options

  • Add clean() method in your Image model. This will check if only one of field (image or url) is provided. Otherwise raise ValidationError.

    • This will handle conditions when you are saving objects using ModelForm.
  • You need to also override save() method of the model. In this check if you have only one of the field provided, otherwise raise IntegrityError.

    • This will handle cases when a attribute of object is saved individually.

Something like:

obj = Image.objects.get(id=<some_id>)
obj.url = some_url
obj.save()
  • If you want to skip 2nd option, you must call full_clean method before saving each existing object.

like

obj = Image.objects.get(id=<some_id>)
obj.url = some_url
obj.full_clean() 
obj.save()

Upvotes: 0

Mr_Spock
Mr_Spock

Reputation: 3835

In your view, you might have something like:

form = Image(request.POST or None)

When you're grabbing the data from the forum, you might have form.cleaned_data['image'] and form.cleaned_data['url']. If one's empty while the other isn't, proceed with whatever you wanted to do. If both are empty, proceed with displaying the error. form.cleaned_data is just a dictionary containing the form values, so you can check to see which ones are empty.

Upvotes: 1

Alireza
Alireza

Reputation: 4516

One way to do this is to consider both of them as not required and then handle the validation in your views, there you can check if either one is present , the form submission was successful, other ways you can output an error to the user.

It was just an idea of how to overcome the issue, i know it won't answer your question (though I think that's not possible in models , but i'm not sure)
hope it helps

Upvotes: 0

Related Questions