django上传图片


1.setting中设置

# 上传文件,资源配置
MEDIA_URL = '/dimples/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'dimples')

2.model

只存储路径

image = models.ImageField(upload_to='image/%Y/%m',default=u'image/default.png',max_length=100)

upload_to=: 指明文件的路径(image/年/月)

3.html中获取图片

例如:

{{ course_org.image }}  只获取了相对地址

正确方式

  • a.在前面加{{ MEDIA_URL }}
{{ MEDIA_URL }}{{ course_org.image }}
  • b.在前面加/dimples/
data-url = "/dimples/{{ course_org.image }}"

4.配置media内部处理类(setting中)

OPTIONS--->context_processors中添加:

'django.core.context_processors.media'

如下:

'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.core.context_processors.media'
            ],
        },

会自动将MEDIA_URL注册到html中

5.配置urls

from django.views.static import serve

配置(上传文件的访问处理函数) dimples的urls:

url(r'^dimples/(?P.*)$', serve, {'document_root': MEDIA_ROOT}),

你可能感兴趣的:(django)