当我尝试保存详细信息时,出现此错误:KeyError:'image'。我无法理解,为什么? views.py中的错误。我想一次上传多张照片
views.py:
@user_passes_test(lambda u: u.is_superuser)
def new_detail(request):
ImageFormSet = modelformset_factory(DetailImage,
form=ImageForm, extra=10)
if request.method == 'POST':
form = DetailForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES,
queryset=DetailImage.objects.none())
if form.is_valid() and formset.is_valid():
detail_form = form.save()
detail_form.save()
for form in formset.cleaned_data:
images = form['image'] # HERE IS THE PROBLEM
photo = DetailImage(detail=detail_form, image=images)
photo.save()
return redirect('/new_detail/')
else:
form = DetailForm(request.POST)
formset = ImageFormSet(queryset=DetailImage.objects.none())
return render(request, 'shop/new_detail.html',
{'form': form,'formset': formset})
forms.py
...
class ImageForm(forms.ModelForm):
image = forms.ImageField()
class Meta:
model = DetailImage
fields = ('image',)
models.py
...
class DetailImage(models.Model):
detail = models.ForeignKey(Detail, related_name='images',
on_delete=models.CASCADE)
image = models.ImageField(upload_to='details', null = True, blank = True)
答案 0 :(得分:0)
KeyError:在您的情况下,“ image”表示您的表单集清除数据中的其中一个表单中没有“ image”键。您应该执行检查。像这样:
mapSource()