Django FileField default file
Asked Answered
T

3

10

I have a model which contains FileField as below

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

The question is how can I add a default file like "{{ MEDIA_ROOT}}/logos/anonymous.jpg" to this filefield ?

Tiki answered 18/7, 2011 at 23:40 Comment(0)
B
16

You can specify the default file to use for that 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')
Breuer answered 18/7, 2011 at 23:42 Comment(3)
how does the default parameter settings.MEDIA_ROOT get interpolated to the proper value in the string?Boisleduc
the path django is going to use in default is (by default): settings.MEDIA_ROOT + '/' + 'your_path', so be sure you place your default file thereUnconscious
Don't think this solution scales across environments? If the production instance runs S3, for example, does something like MEDIA_ROOT work? And I think the hardcoded FileSystemStorage also doesn't work.Clodhopping
T
2

in your models file

logo = models.FileField(upload_to='logos', default='logos/logo.png')
titre = models.CharField(max_length=100)

in your settings add

MEDIA_ROOT =  os.path.dirname(os.path.abspath(__file__))
MEDIA_URL = '/logos/'
Trackandfield answered 17/7, 2018 at 17:10 Comment(0)
W
0

Since the solution above was not really working for me (settings.MEDIA_ROOT is not beeing interpreted and I want to gitignore the media folder) here's a (somehow hacky) solution which allows me to specify a static file as a default in an Image/FileField:

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

The hacky part is that if you have a MEDIA_URL with more than one level '..' won't be enough (but then you can simply go with '../../').

Wellread answered 4/1, 2017 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.