我试图建立一个使用ImageField接受用户上传图像的webapp,但是我似乎无法弄清楚如何保存上传的图像。我的媒体文件夹为空,即使似乎没有任何错误。
经历了很多教程都没有用。我得到了基本概念,创建了一个表单,建立了模型,在settings.py中设置了媒体,在视图中处理了上传,并且正在使用图像上传表单获得一个工作视图,但是上传图像并不能保存。
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
urlpatterns = [
path('embed/', embed, name = 'embed'),
path('success', success, name = 'success'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
forms.py
class imguploadform(forms.ModelForm):
class Meta:
model = imgupload
fields = ['title', 'image']
models.py
class imgupload(models.Model):
title = models.CharField(max_length = 20)
image = models.ImageField(upload_to="media/images/", default = None)
def __str__(self):
return self.title
views.py
def embed(request):
if request.method == 'POST':
form = imguploadform(request.POST, request.FILES)
if form.is_valid():
newimg = imgupload(title=request.POST['title'], image=request.FILES['image'])
newimg.save()
return redirect('success')
else:
form = imguploadform()
return render(request, 'webapp/imgupload.html', {'form' : form})
def success(request):
return HttpResponse("Successfully uploaded")
imgupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
另一件事要注意,管理面板不会显示图像模型
答案 0 :(得分:0)
以下在我的机器whoes os系统上工作的代码是ubuntu18,带有最新的Django和枕头
models.py
class Imgupload(models.Model):
title = models.CharField(max_length=20)
image = models.ImageField(upload_to="images/", default=None)
def __str__(self):
return self.title
views.py
def embed(request):
if request.method == "POST":
form = Imguploadform(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("success")
else:
form = Imguploadform()
img = Imgupload.objects.last()
return render(request, "webapp/imgupload.html", {"form": form, "img": img})
def success(request):
return HttpResponse("Successfully uploaded")
imgupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
{% if img %}
Image uploaded latest:
<img src="{{ img.image.url }}">
{% endif %}
</body>
</html>