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 ?

brsbilgic
  • 11,613
  • 16
  • 64
  • 94

3 Answers3

15

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')
rolling stone
  • 12,668
  • 9
  • 45
  • 63
  • 11
    how does the default parameter `settings.MEDIA_ROOT` get interpolated to the proper value in the string? – seanmus Apr 20 '17 at 19:47
  • 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 there – Pedro Muñoz Dec 09 '20 at 09:48
  • 2
    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. – ankush981 Jun 13 '21 at 15:19
1

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/'
Martin
  • 2,411
  • 11
  • 28
  • 30
Geyd
  • 11
  • 1
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 '../../').

Papers.ch
  • 106
  • 1
  • 3