Home > Net >  Django video field contains url or file
Django video field contains url or file

Time:01-29

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.

CodePudding user response:

Having only one option

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.

Checking at a controller level (Simple solution)

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.

Changing the model and handling at service level (Recommended)

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.

CodePudding user response:

In Django, a video field is a type of field that allows you to store video files in your database. You can use a FileField or ImageField with upload_to attribute to store video files. You can also store video URLs in a URLField or a TextField if you want to embed videos from other websites. It depends on your use case and the requirements of your project.

from django.db import models

class MyModel(models.Model):
    video = models.FileField(upload_to='videos/')

the video field is a FileField that allows you to upload video files. The upload_to attribute specifies the subdirectory within your MEDIA_ROOT where the files will be stored.

  • Related