Django FileField Default File

I have a model that contains a FileField as shown below

 class Employer(models.Model): logo = models.FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT), upload_to='logos') 

The question is how to add a default file, for example, "{{MEDIA_ROOT}} / logos / anonymous.jpg" in this field?

+7
source share
2 answers

You can specify the default file for this field as follows:

 class Employer(models.Model): logo = models.FileField(storage=FileSystemStorage(location=settings.MEDIA_ROOT), upload_to='logos', default='settings.MEDIA_ROOT/logos/anonymous.jpg') 
+11
source

Since the above solution didn’t actually work for me (.MEDIA_ROOT settings are not interpreted, and I want gitignore in the media folder) here is a (somehow hacked) solution that allows me to specify the default static file in the image / FileField:

 image = models.ImageField(upload_to="image/", default='..{}img/dashboard/default-header.jpg'.format(settings.STATIC_URL), verbose_name=_(u'image')) 

The hacker part is that if you have MEDIA_URL with more than one level "..", it will not be enough (but then you can just go with "../../ ').

0
source

All Articles