zoukankan      html  css  js  c++  java
  • 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">
  • 相关阅读:
    python类内置方法之__call__
    selenium之python源码解读-webdriver继承关系
    Jmeter之JDBC类型组件
    Jmeter逻辑控制之if控制器
    Java连接MySQL Warning: Establishing SSL connection without server's identity verification is not recommended
    Python3 Windows服务器简单实现 手机访问
    如何在C语言 C++里面调用 DOS命令
    常用DOS命令(1) color,dir,copy,shutdown,mkdir(md),rmdir(rd),attrib,cd
    Java实现队列
    Java 实现 栈
  • 原文地址:https://www.cnblogs.com/saptechnique/p/13213182.html
Copyright © 2011-2022 走看看