无法使用django显示个人资料图像



我正在学习一个基本的django上传图像教程,我已经陷入了困境。我试图让用户上传一个文件,将其存储在文件夹中,然后将地址保存到数据库中的图像中。这部分似乎都在起作用。然后,我尝试使用一个简单的页面来显示所有图像,以确保其正常工作,并且HTML中的img标记保持src为";未知";。我不确定到底是什么问题,因为没有任何错误。

视图.py

from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.views.generic.edit import CreateView
from django.views.generic import ListView
from .models import UserProfile

# Create your views here.

class CreateProfileView(CreateView):
template_name = "profiles/create_profile.html"
model = UserProfile
fields = "__all__"
success_url = "/profiles"

class ProfilesView(ListView):
model = UserProfile
template_name = "profiles/user-profiles.html"
context_object_name = "profiles"

型号.py

from django.db import models
# Create your models here.
class UserProfile(models.Model):
image = models.ImageField(upload_to="image")

用户配置文件.html

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Profiles</title>
</head>
<body>
<ul>
{% for profile in profiles %}
<li>
<img src="{{ profile.url }}">
</li>
{% endfor %}
</ul>
</body>
</html>

Forms.py

from django import forms 
class ProfileForm(forms.Form):
user_image = forms.ImageField()

/profiles中的Urls.py

from django.urls import path
from . import views
urlpatterns = [
path("", views.CreateProfileView.as_view()),
path("list", views.ProfilesView.as_view())
]

项目文件夹中的Urls.py

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

设置.py

"""
Django settings for feedback project.
Generated by 'django-admin startproject' using Django 4.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--#-h(v7)m6p4rr&fs#7&caa9!$w4!#xzhkioljoy34v3@o!%@%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []

# Application definition
INSTALLED_APPS = [
'reviews',
'profiles',
'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 = 'feedback.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 = 'feedback.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Password validation
# https://docs.djangoproject.com/en/4.0/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.0/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.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
#path for files to be stored
MEDIA_ROOT = BASE_DIR / "uploads"
MEDIA_URL = BASE_DIR = "/user-image/" #you can define the URL to whatever you want between '/ /'

您使用.image字段的.url,因此:

{% for profile in profiles %}
<li>
<img src="{{profile.image.url}}">
</li>
{% endfor %}

相关内容

最新更新