运行代码时没有错误,图像将存储在数据库中,但不会显示在网页中,我在这里发布源代码 我的申请页面代码
{% 扩展 'shop/layouts/main.html' %}
{% 块标题 %} 注册|网上购物 {% 结束块标题 %}
{% 块内容 %}
<section class="py-5 text-center container" style="margin-top: 70px;">
<div class="row py-lg-5">
<div class="col-lg-6 col-md-8 mx-auto">
<h1 class="fw-light">Bestsellers</h1>
<p class="lead text-muted">Our most popular products based on sales.updated honourly</p>
<p>
<a href="#" class="btn btn-primary my-2">Already User</a>
<a href="#" class="btn btn-secondary my-2">Register</a>
</p>
</div>
</div>
</section>
<section class="bg-light py-4 my-5">
<div class="container">
<div class="row">
<div class="col-12">
<h4 class="mb-3">Categories</h4>
<hr style="border-color:#b8bfc2">
</div>
{% for item in category %}
<div class="col-md-4 col-lg-3">
<div class="card my-3">
<img src="{{item.image.url}}" class="card-image-top" alt="Categories">
<div class="card-body">
<h5 class="card-title text-primary">{{item.name}}</h5>
<p class="card-text">{{ item.description }}</p>
<a href="" class="btn btn-primary btn-sm">View Details</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</section>
{% 末端嵌段含量 %}
models.pycode
from django.db import models
import datetime
import os
def getFileName(request,filename):
now_time=datetime.datetime.now().strftime("%Y%m%d%H:%M:%S")
new_filename="%s%s"%(now_time,filename)
return os.path.join('uploads/',new_filename)
# Create your models here.
class Catagory(models.Model):
name=models.CharField(max_length=150,null=False,blank=False)
image=models.ImageField(upload_to=getFileName,null=True,blank=True)
description=models.TextField(max_length=500,null=False,blank=False)
status=models.BooleanField(default=False,help_text="0-show,1-Hidden")
created_at=models.DateTimeField(auto_now_add=True)
def __str__(self) :
return self.name
class Product(models.Model):
catagory=models.ForeignKey(Catagory,on_delete=models.CASCADE)
name=models.CharField(max_length=150,null=False,blank=False)
vendor=models.CharField(max_length=150,null=False,blank=False)
product_image=models.ImageField(upload_to=getFileName,null=True,blank=True)
quantity=models.IntegerField(null=False,blank=False)
original_price=models.FloatField(null=False,blank=False)
selling_price=models.FloatField(null=False,blank=False)
description=models.TextField(max_length=500,null=False,blank=False)
status=models.BooleanField(default=False,help_text="0-show,1-Hidden")
trending=models.BooleanField(default=False,help_text="0-default,1-Trending")
created_at=models.DateTimeField(auto_now_add=True)
def __str__(self) :
return self.name
setting.py文件
"""
Django settings for karthi_django project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-83vl+-z)2vz9+u*=a#%00v2^%i6^v^rg-*#_!=@nqvezk=4^)-"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'jazzmin',
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"shop"
]
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 = "karthi_django.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 = "karthi_django.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = "static/"
MEDIA_URL = "/images/"
MEDIA_ROOT = (BASE_DIR,"images")
STATICFILES_DIRS = [
BASE_DIR / "static",
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
url.py
"""karthi_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
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("shop.urls")),
]
if settings.DEBUG:
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
view.py
from django.shortcuts import render
from . models import *
# Create your views here.
def home(request):
return render(request, "shop/index.html")
def register(request):
return render(request, "shop/register.html")
def collections(request):
catagory=Catagory.objects.filter(status=0)
return render(request,'shop/collections.html',{"catagory":catagory})
admin.py
from django.contrib import admin
from.models import *
admin.site.register(Catagory)
admin.site.register(Product)
MEDIA_URL =“图片/”
删除 MEDIA_URL 中的起始斜杠。
在 html 文件中,将图像的 src 替换为 {{item.img.url}} 而不是 {{item.image.url}}。
图片需要替换为img。