brsbilgic
brsbilgic

Reputation: 11833

Django FileField default file

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 ?

Upvotes: 10

Views: 19345

Answers (3)

Geyd
Geyd

Reputation: 21

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/'

Upvotes: 2

Papers.ch
Papers.ch

Reputation: 128

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 '../../').

Upvotes: 0

rolling stone
rolling stone

Reputation: 13016

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')

Upvotes: 16

Related Questions