Django FileField default file

最后都变了- 提交于 2021-02-16 05:00: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 ?


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!