【发布时间】:2019-08-11 19:19:02
【问题描述】:
我在 Django 中创建了一个简单的表单,它只包含一个表单输入字段,即图像字段。我的目标是允许用户上传图像文件,即 JPEG、JPG、SVG、PNG。上传后,我想编写一些代码将图像文件转换为 PNG,然后将其存储在我的数据库中。我应该如何编写这段代码以及在哪里编写它?您可以在下面查看我当前的代码。我是 Django 的初学者,需要一些帮助。
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
网站/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('myapp.urls')),
]
urlpatterns = urlpatterns + static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
class Image(models.Model):
"""Image upload model"""
image = models.ImageField(upload_to = 'media', default = 'media/sample.png')
created_date = models.DateTimeField(auto_now = True)
def __str__(self):
return str(self.id)
forms.py
from django import forms
from myapp.models import Image
class ImageForm(forms.ModelForm):
"""Image upload form"""
class Meta:
model = Image
exclude = ('created_date',)
views.py
from django.shortcuts import render
from django.db import models
from django.views.generic import TemplateView, CreateView
from myapp.forms import ImageForm
from django.urls import reverse_lazy
from PIL import Image
class BaseView(TemplateView):
template_name = "base.html"
class ImageView(CreateView):
template_name = "insert_image.html"
form_class = ImageForm
success_url = reverse_lazy("base")
insert_image.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title> Insert an image </title>
</head>
<body>
<h1> Please upload an image below </h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form.as_p}}
<button type="submit"> Submit </button>
</form>
</body>
</html>
base.html
<!DOCTYPE html>
<html>
<head>
<title> Thanks! </title>
</head>
<body>
<h1> Thanks for uploading! </h1>
<button> <a href = '{% url "insert_image" %}' style="text-decoration:
none;"> Return </button> </a>
</body>
</html>
【问题讨论】: