首页 > 解决方案 > 我的图像在 django 中显示为损坏的文件

问题描述

我试图建立一个网站,允许用户发布他们想要销售的产品的产品图片和描述。但我得到了一个破碎的图像缩略图。

这是我的 settings.py 文件

"""
Django settings for mum project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'tbe4^5o02%t@$e4n551llb@_5d_!l+8j2+je_a5gl6610zmfu)'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'products.apps.ProductsConfig',
    '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 = 'mum.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 = 'mum.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

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

STATICFILES_DIR = (
    os.path.join(BASE_DIR, 'static'),
)

这是我的models.py

from django.db import models
from django.utils import timezone
# Create your models here.

class Products(models.Model):
    author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
    product_name = models.CharField(max_length=300)
    product_description = models.CharField(max_length=500)
    product_image = models.ImageField(blank=True, null=True, upload_to="image/")
    published_date = models.DateTimeField(auto_now_add=True, blank=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.product_name


这是我的forms.py

from django import forms
from .models import Products


class ProductsForm(forms.ModelForm):
    class Meta:
        model = Products
        fields = ('product_name', 'product_description',  'product_image',)

        widgets = {
            'product_name': forms.TextInput(attrs={'class': 'form-control', "placeholder": 'Enter Product Name',  'rows': 20,  'cols': 60,}),
            'product_description': forms.TextInput(attrs={'class': 'form-control', "placeholder": 'Enter Product Description',  'rows': 20, 'cols': 100,}),
        }

这是我的项目名称/网址

from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('products.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

这是我的应用名称/网址

from . import views

urlpatterns = [
    path('', views.homepage, name="homepage"),
    path('products/', views.products_list, name="products_list"),
    path('products/product/<int:pk>/', views.product_detail, name="product_detail"),
    path('products/add_product/', views.add_product, name="add_product"),
]

这是我的意见.py

from django.shortcuts import render, redirect
from .models import Products
from .forms import ProductsForm
from django.utils import timezone
# Create your views here.

def homepage(request):
    return render(request, 'products/homepage.html')

def products_list(request):
    post = Products.objects.order_by('-published_date')

    context = {
        'posts': post
    }
    return render(request, 'products/products_list.html', context)

def product_detail(request, pk=None):
    detail = Products.objects.get(pk=pk)
    context = {
        'detail': detail,
    }
    return render(request, 'products/products_detail.html', context)


def add_product(request, pk=None):
    if request.method == "POST":
        form = ProductsForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect('products_list')
        form = ProductsForm()
    else:
        form = ProductsForm()

    context = {
        'form': form
    }
    return render(request, 'products/add_product.html', context)

这是我的 products_list.html

{% extends 'base.html' %}
{% block content %}

{% for post in posts %}
    {{ post.author }}
<br>
    <a href="{% url 'product_detail' pk=post.pk %}">{{ post.product_name }}</a>
<br>
    {{ post.product_description }}
<br>
{% if product_image %}
   <img src="{{ post.product_image }}"/>
{% endif %}
<br>
    {{ post.published_date }}
<br>
{% endfor %}

{% endblock %}

这是我的 product_detail.html

{% extends 'base.html' %}
{% load static %}
{% block content %}

    {{ detail.author }}
<br>
    {{ detail.product_name }}
<br>
    {{ detail.product_description }}
<br>
    <img src="{{ detail.product_image }}"/>
<br>

{% endblock %}

标签: pythondjango

解决方案


您需要访问以下url属性product_image

<img src="{{ post.product_image.url }}"/>

推荐阅读