该网站允许用户上传图像,并将被编辑和显示给用户。(学习使用Pillow进行图像编辑)。它在终端中没有错误,图像正在保存,但编辑后没有显示。图像生成方式是否存在问题?在JavaScript中?
终端看起来也很好,显示如下:
[03/Aug/2023 15:28:32] "GET / HTTP/1.1" 200 1445
[03/Aug/2023 15:28:37] "POST / HTTP/1.1" 200 1521
字符串
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Image Editor</title>
<style>
img {
max-width: 400px;
max-height: 400px;
}
</style>
</head>
<body>
<h1>Image Editor</h1>
<form action="{% url 'edit_image' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="image_file" id="image_file" onchange="previewImage(event)">
<input type="submit" value="Upload and Edit">
</form>
<div id="imagePreview">
<h2>Uploaded Image Preview:</h2>
<img id="preview" src="" alt="Uploaded Image">
</div>
{% if edited_image %}
<h2>Edited Image:</h2>
<img src="{{ edited_image.url }}" alt="Edited Image">
{% endif %}
<script>
function previewImage(event) {
const fileInput = event.target;
const imagePreview = document.getElementById("imagePreview");
const preview = document.getElementById("preview");
if (fileInput.files && fileInput.files[0]) {
const reader = new FileReader();
reader.onload = function (e) {
preview.src = e.target.result;
};
reader.readAsDataURL(fileInput.files[0]);
imagePreview.style.display = "block";
} else {
preview.src = "";
imagePreview.style.display = "none";
}
}
</script>
</body>
</html>
型
网址:views.py
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from PIL import Image
from io import BytesIO
import os
import uuid
def index(request):
edited_image = None
if request.method == 'POST' and request.FILES['image_file']:
image_file = request.FILES['image_file']
# Process the uploaded image using Pillow
edited_image = process_image(image_file)
return render(request, 'index.html', {'edited_image': edited_image})
def process_image(image_file):
image = Image.open(image_file)
# Image processing logic using Pillow or OpenCV can be done here.
# For simplicity, let's just save the edited image and return its path.
# Example: Converting the image to grayscale
edited_image = image.convert('L')
# Generating a new random filename for the edited image
edited_image_name = f"edited_image_{uuid.uuid4().hex}.jpg"
edited_image_path = os.path.join('media', edited_image_name)
edited_image.save(edited_image_path, format='JPEG')
return edited_image_path
型
项目urls.py:
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('image_editor.urls'))
]
# Serve media files during development
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
型
网址:settings.py
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 = ''
# 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',
'image_editor',
]
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 = 'djangoPhotoEditor.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'image_editor'/'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 = 'djangoPhotoEditor.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/'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
型
1条答案
按热度按时间ilmyapht1#
在views.py
字符串
os.path.join返回字符串。您将此字符串添加到上下文中,然后在模板中尝试访问不存在的edited_image.url。
顺便说一句,您将位置硬编码为“媒体”,而不是使用您在settings.py中设置的媒体位置。我建议将此更改为
型
就你的主要问题而言,有很多方法可以获得URL。一个简单的解决方案,应该与您的现有代码(未测试)将更改您的视图代码的索引方法如下:
型
然后在模板中替换:
型
与:
型