如何在不使用django表单的情况下存储图像



html表单:

<form action = "{% url 'newcomplaint' %}" class = 'newc' method = "post" enctype = "multipart/form-data" >
{ % csrf_token % }
<div class = "form-group" >
<label for = "fileToUpload" > Add an image(optional) < /label >
<input type = "file" name = "fileToUpload" id = "fileToUpload" >
</div >
<button type = "submit" class = "btn btn-dark bb" > Post New Complaint < /button >
</form >

views.py:我在这里得到MultiValueDictKeyError at /hood/new

def newcomplaint(request):
if request.method == "POST":
# I dont know how to store a image here
image = request.FILES['fileToupload']
#print(image)
return HttpResponse('works')

型号.py

from django.db import models
from django.core.exceptions import ValidationError 
from django.contrib.auth.models import User
class Complain(models.Model):
image = models.ImageField(upload_to='images/', blank=True)

我看到的所有解决方案都是使用django表单完成的,我想避免这种情况,因为我制作了一个更大的表单,其中包含图像字段和一些其他输入(并添加了样式和Js检查以进行验证(。

因此,如何从表单中检索文件并将其存储在django中。

您的代码希望fileToupload是关键字,但是,您的表单使用fileToUpload

我有一个打字错误,还找到了一个如何在没有表单的情况下将文件/图像存储在django中的解决方案

我的工作代码:views.py

def newcomplaint(request):
if request.method == "POST":
newcomplaint = Complain.objects.create(
user=request.user,
title=request.POST['title'],
content = request.POST['content'],
ran = request.POST['range'],
lati = request.POST['lati'],
longi = request.POST['longi'],
)
if len(request.FILES) == 0:
print('no files')
else: 
_, file = request.FILES.popitem()
file = file[0]
newcomplaint.image = file
newcomplaint.save()


return HttpResponse('works')

有一个打字错误。你已经写了fileToupload。应该是fileToUpload

最新更新