7.2.media文件设置及使用

上传文件到media目录下

设置图片存放位置

hello_django/settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

配置图片上传子目录

organization/models.py

class CourseOrg(models.Model):
    ...
    image = models.ImageField(max_length=100, upload_to='org/%Y/%m', verbose_name='机构图片')
    ...

提示: upload_to='org/%Y/%m'中,%Y为当前年份,%m为当前月份

从media目录下读取文件

注册media上下文解释器

hello_django/settings.py

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'django.template.context_processors.media',
            ],
        },
    },
]

添加media的url

hello_django/urls.py

from django.conf.urls import url
from django.views.static import serve

from hello_django.settings import MEDIA_ROOT

urlpatterns = [
    ...
    # 配置上传文件的访问处理函数
    url(r'^media/(?P<path>.*)$', serve, {"document_root": MEDIA_ROOT}),
]

模板中引用图片

templates/org-list.html

{% for org in all_org %}
    <img ... data-url="{{ MEDIA_URL }}{{ org.image }}"/>
{% endfor %}

Last updated

Was this helpful?