FileField Model Required

76 views
Skip to first unread message

cyril....@gmail.com

unread,
Aug 14, 2020, 3:34:31 PM8/14/20
to Django users
Hi,

Is it possible to mark a FileField in my model as required

My model looks like :
class FileUpload(models.Model):
owner = models.CharField(max_length=200,blank=False, null=False)
record = models.FileField(upload_to=path_and_rename,blank=False, null=False)

1st statement :
According to what i have read the blank and null parameter are not necessary
and only the parameter "upload_to" and "storage" are availables

2nd statement : 
Secondly, it seems that the field validation are done at the form level or serializer level.

I would like to know if these 2 statements are true?

when I use python manage.py shell and make a test of creating a FileUpload object and save it, i dont get any error saying the that filefield is required :
## steps :
test = FileUpload(owner="test")
test.save()

## expected :
Error : filefield "record" is required!

## actual behavior :
save the object without error

Is it possible to put the filefield as required at the model level?
or
Do i have to make the validation of the field before/at an upper level?

Thank you
Cyril

cyril....@gmail.com

unread,
Aug 14, 2020, 4:25:32 PM8/14/20
to Django users
The solution I have found is overriding the save function from the model class:

class FileUpload(models.Model):
owner = models.CharField(max_length=200,blank=False, null=False)
record = models.FileField(upload_to=path_and_rename)

def save(self, force_insert=False, force_update=False, *args, **kwargs):
    if not bool(self.record):
         raise ValidationError("Record is required")
         super(FileUpload, self).save(force_insert, force_update, *args, **kwargs)


Is there another way to do it?
Best regards,
Cyril
Reply all
Reply to author
Forward
0 new messages