问题
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 ?
回答1:
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')
回答2:
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 '../../').
回答3:
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/'
来源:https://stackoverflow.com/questions/6740715/django-filefield-default-file