由于这个问题我已经遇到过很多次了,却找不到解决办法,所以我需要帮助
这是我的设置文件。我已经配置了媒体根
from pathlib import Path
import os
import django_heroku
import django
# 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 = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
]
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 = 'testimage.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'testimage.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/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,"static")]
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
django_heroku.settings(locals())
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
这是一个简单的模型用来添加和显示图像
from django.db import models
# Create your models here.
class Images(models.Model):
photo = models.ImageField(blank=True, null=True, default=None)
title = models.CharField(max_length=250)
def __str__(self):
return self.title
这是我的views.py和模板
from django.shortcuts import render
from home.models import Images
# Create your views here.
def index(request):
images = Images.objects.all()
context = {
'images':images
}
return render(request,'home.html',context)
home。
{%for i in images %}
<img src="{{i.photo.url}}" alt="">
{%endfor%}
每次我尝试加载那个页面,我总是得到这个错误:
[15/Feb/2021 11:57:12] "GET /media/20210129_205930.jpg HTTP/1.1" 404 2130
[15/Feb/2021 11:57:12] "GET /media/20201227_111422.jpg HTTP/1.1" 404 2130
我知道这是告诉有问题的媒体路径,但我检查了它,但没有找到任何错误的点。请看
似乎您还没有在url.py
文件中添加媒体url,所以您可以这样做
# make your imports
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
....
]
# for Debugging
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我希望您完成了上面提到的所有url.py代码image是一个文件所以你需要请求像这样的文件
def index(request.FILES, request.POST):
images = Images.objects.all()
context = {
'images':images
}
return render(request,'home.html',context)
在你的HTML文件格式标签中使用enctype
<form action="{% url 'name' %}" method'POST' enctype="multipart/form-data">
和删除你默认从你的图像类,如果你想你的图像可以是空白的=True这里不需要默认值在你的模型中你没有定义路径当你的图像需要被存储的时候像这样
profile_pic = models.ImageField(upload_to='profile_pics',default='default.png',)
并在主url .py中添加
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我希望这对你有帮助,如果你有任何错误告诉我