Reputation: 26
How to make only one field of these two fields? is it possible?
class MyModel(models.Model):
video_file = models.FileField(blank=True)
video = models.URLField(blank=True)
def clean(self, *args, **kwargs):
if not self.video_file and not self.video: # This will check for None or Empty
raise ValidationError({'video_file': 'Even one of field1 or field2 should have a value.'})
elif self.video_file and self.video: # This will check for None or Empty
raise ValidationError({'video_file': 'Even one of field1 or field2 should have a value.'})
if self.video == '':
self.video = self.video_file.url
super(MyModel, self).save(*args, **kwargs)```
**UPDATED**
I think this is the solution, my bad.
Upvotes: 0
Views: 45
Reputation: 128
The easiest solution might be to not accept 2 different types, and only support either Image upload or Image URL. I'd suggest Image upload only if you're going to implement this solution.
However, if having those 2 options is a requirement you can take a look at the solutions I've listed below.
One solution is to check if both fields are populated at the controller level, or View
in django jargon. If both are populated you can throw some error and handle it from there.
The above solution might work, but that wouldn't be the ideal solution for the long run.
I'd recommend you to change your model to only have a FileField
, then in service layer you can directly upload if user uploads a file, however if user passes a URL you can download the image and save it.
You can also make the DB field a UrlField
, and if user uploads a file, you can upload it to some external storage bucket like s3 or cloudinary and save the URL in your database.
As for the constraint, you can apply the constraint as mentioned above in solution 2 of adding the constraint in controller or some other way using django magic.
Upvotes: 1