从Django模型

时间:2017-09-29 21:15:16

标签: python django django-models django-templates

我正在制作一个简单的应用程序(Django版本1.11 + python3.5 +)。我想在Django模型的主页(网络应用程序)上显示图像。我可以从Django管理面板成功上传。但图像无法正常呈现。图像未显示在主页中。这是我的HTML文件。

{% extends "shop/base.html" %}
{% block content_area %}
{% for name in products %}
<div class="col-lg-3 col-md-3">
    <div class="main_content_sidebar">
        <div class="content_title">
            <h2>{{name.product_name}}</h2>
        </div>
        <div class="image_space">
            <img src="{{name.product_image.url}}" class="img-thumbnail" alt="">
        </div>
        <div class="content_p">
            <p>Retail Price:{{name.product_retail_price}}</p>
            <p>Quantity: {{name.product_quantity}}</p>
            <p>Date: {{name.product_sell_date}}</p>
        </div>
    </div>
</div>
{% endfor %}
{% endblock %}

这是mysite(项目)&gt;&gt; urls.py

from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static

from django.conf import settings
urlpatterns = [
    url(r'^shop/',include('shop.urls')),
    url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

这是我的models.py文件。

class ProductsName(models.Model):
    product_name=models.CharField('name', max_length=50)
    product_retail_price=models.IntegerField('retail price TAKA')
    product_quantity = models.IntegerField('quantity')
    product_sell_date=models.DateTimeField('buy date', auto_now_add=True)
    product_image = models.ImageField(upload_to='upload/', blank=True, null=True)

    def __str__(self):
        return self.product_name

setting.py文件

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'shop.apps.ShopConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Dhaka'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'shop/images/')
MEDIA_URL = '/media/'

当我访问我的主页时,我看不到任何图像。但我看到图像链接如果我打开我的浏览器开发工具。 chrome dev tool

如果我点击chrome dev工具中的图片链接。我收到django doesn/t found that image url错误。

我的文件夹结构也是:

mysite的 店 manage.py path_to db.sqlite3

1 个答案:

答案 0 :(得分:0)

问题是您的MEDIA_ROOT未被提供,Django无法附加正确的网址。在您的项目中,urls.py在最后添加以下内容:

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

在setttings.py中添加正确的路径:

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