我收到了一个错误,
/ accounts / upload_save /中的MultiValueDictKeyError
"'图像'" 。
我正在制作文件上传系统。如果我选择文件并放入&#34; SEND&#34;按钮,所选图像被发送到模型。但是现在,当我选择没有图像并且放置&#34; SEND&#34;按钮,错误发生。我想制作一个系统,如果我没有选择图像并放置&#34; SEND&#34;按钮,显示<div class="container" id="photoform">
{% if form.errors %}
<div class="alert alert-danger" role="alert">
<p>You should select at least one photo</p>
</div>
{% endif %}
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 30%;">
<span class="btn btn-primary btn-lg">
File Select1
<input type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 30%;">
<span class="btn btn-primary btn-lg">
File Select2
<input type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-primary btn-lg">
File Select3
<input type="file" name="image3">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="SEND" class="form-control">
</div>
</form>
</div>
消息。
我在photo.html中写道
@login_required
@csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.image = request.FILES['image']
data.save()
else:
print(form.errors)
else:
form = UserImageForm()
return render(request, 'registration/photo.html', {'form': form})
我在views.py中写道
urlpatterns = [
url(r'^upload_save/$', views.upload_save, name='upload_save'),
]
在urls.py中
class UserImageForm(forms.ModelForm):
class Meta:
model = ImageAndUser
fields = ('image',)
在forms.py
中class ImageAndUser(models.Model):
user = models.ForeignKey("auth.User", verbose_name="imageforegin")
image = models.ImageField(upload_to='images', null=True, blank=True,)
date = models.IntegerField(max_length=100,null=True)
在models.py
中noexcept
我真的无法理解为什么会发生这种错误,因为我写了if-else语句,并且我在else语句中打印(form.errors)。我该怎么做才能解决这个问题?我怎么写呢?
答案 0 :(得分:0)
class UserImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = ImageAndUser
fields = ('image',)
并更改您的views.py
@login_required
@csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.image = form.cleaned_data['image']
data.save()
else:
print(form.errors)
else:
form = UserImageForm()
return render(request, 'registration/photo.html', {'form': form})