• Django Media URL 文件上传 配置


    如果在url中没有配置media,即使在settings设置了MEDIA_ROOT,也无法正常显示图片。

    会遇到如下错误

    Using the URLconf defined in me_blog.urls, Django tried these URL patterns, in this order:
    
        blog/
        admin/
    
    The current path, media/banner/发货-2.jpg, didn't match any of these.
    

    如何解决呢?需要一次做出如下操作:

    1.正确配置MEDIA_URL和MEDIA_ROOT

    settings中配置。

    MEDIA_URL = '/media/'
    # 设置上传文件的路径
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')   # 指定根目录
    

     2.在Model中应用配置

    class ProductInfo(models.Model):
        # 商品模型:pic为该商品的图片在项目中存储的相对路径
        pic = models.ImageField(verbose_name="图片路径", default="image/default.png", upload_to='df_goods/image/%Y/%m', null=True, blank=True)  # 商品图片
    

     3.配置url路由

    from django.views.static import serve  # 上传文件处理函数
    
    from .settings import MEDIA_ROOT  # 从配置中导入MEDIA_ROOT
    
    
    urlpatterns = [
        url(r'^media/(?P<path>.*)$', serve, {"document_root":MEDIA_ROOT})
    ]
    

     4.配置templates模板

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            '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.template.context_processors.media',  # 将media_url上传文件路径注册到模板中
                ],
            },
        },
    ]
    

     5.在页面中使用

    <img src="{{ MEDIA_URL }}{{ product.pic }}">
    其中{{ product.pic }}为商品的路径

    页面经过渲染之后,在浏览器中会显示为:

    <img src="/media/product/image/2019/05/product_detail.jpg">
  • 相关阅读:
    while for循环
    Python模块
    python内置函数
    【简介】《GM/T 0034-2014 基于SM2密码算法的证书认证系统密码及其相关安全技术规范》
    Markdown的Diagrams
    密码设备管理-对称密钥管理
    TortoiseSVN的简单使用
    Android Studio安装后的设置
    Android Studio升级后,新建Activity后setContentView(R.layout.activity_layout_main);中R变红
    简介Floyd算法
  • 原文地址:https://www.cnblogs.com/saptechnique/p/13213182.html
Copyright © 2020-2023  润新知