Django图像字段默认静态文件 [英] Django image field default static file

查看:130
本文介绍了Django图像字段默认静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以将静态图像文件用作ImageField的默认值?

I was wondering if there is a way to use an static image file as a default for an ImageField?

我问这是因为,如果您编写类似这是因为首先,我无法将媒体文件夹上传到我的github存储库,因为我在其中存储了用户上传的内容,并且默认文件始终是相同的,因此我想从静态提供默认值,但用户要从媒体上传

I'm asking this because if you write something like this because first, I'm not able to upload media folder to my github repository because I store in there the user uploads, and the default file always be the same, so I want to serve the default from static but the user uploads from media directory.

如果使用此命令:

image = models.ImageField(upload_to=/upload/folder/, default=/img/default.jpg, blank=True, null=True)

它将尝试从媒体目录加载默认图像。

It will try to load the default image from the media directory.

推荐答案

更新:该答案不再起作用。从1.9版开始,Django从文件路径中删除前导 / 并将其转换为相对路径,然后附加 / media / 到路径。

UPDATE: This answer no longer works. Since version 1.9, Django removes the leading / from the file path to convert it to a relative path and then appends /media/ to the path.

此更改是由于以下票证引起的: https://code.djangoproject.com/ticket/25905

This change was made due to this ticket: https://code.djangoproject.com/ticket/25905

替代:我喜欢 此答案

Alternative: I like this answer as an alternative.

原始答案:

首先,请查看以下两条路径:

First, look at the these two paths:

/img/default.jpg    -   Absolute Path (starts with slash)
img/default.jpg     -   Relative Path (doesn't start with slash)

现在,如果您的默认路径为绝对,则Django将不会转换网址到 / media /.../。 Django仅转换相对路径

Now, if your default path is absolute, then Django will not convert the url to /media/.../. Django only converts the relative paths.

因此,如果要从 static 文件夹,您可以设置文件的绝对路径,例如- /static/img/default.jpg

So, if you want to serve the default file from static folder, you can just set an absolute path to your file like - /static/img/default.jpg.

其他:

您甚至可以对此进行验证。 Django使用 urllib.parse.urljoin 创建URL。试试这个:

You can even verify this. Django uses urllib.parse.urljoin to create the url. Try this:

>>> media_url = '/media/'
>>> abs_url   = '/img/default.jpg' # absolute url
>>> rel_url   = 'img/default.jpg'  # relative url

>>> from urllib.parse import urljoin # in Python 2: from urlparse import urljoin

>>> urljoin(media_url, abs_url) # test with absolute url
'/img/default.jpg'
>>> urljoin(media_url, rel_url) # test with relative url
'/media/img/default.jpg'

这篇关于Django图像字段默认静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆