django - 当我尝试在 django 中更新多个图像时出现错误
问题描述
当我想编辑与每个产品相关的照片时,我在编辑产品模型时遇到错误。请帮忙。对不起,我的英语不好:) 这个错误信息:
/account/villa/update/13 'PhotoVillaForm' 对象的 AttributeError 没有属性 'cleaned_data'
更新视图:
def VillaEdit(request, pk):
villa = get_object_or_404(Villa, id=pk)
ImageFormset = modelformset_factory(PhotoVilla, fields=('photo',), extra=4)
if request.method == "POST":
form = VillaEditForm(request.POST or None, instance=villa)
formset = ImageFormset(request.POST or None, request.FILES or None)
if form.is_valid() or formset.is_valid():
form.save()
data = PhotoVilla.objects.filter(id_villa=pk)
for index, f in enumerate(formset):
if f.cleaned_data:
if f.cleaned_data['id'] is None:
photo = PhotoVilla(villa=villa, photo=f.cleaned_data.get('photo'))
photo.save()
elif f.cleaned_data['photo'] is False:
photo = PhotoVilla.objects.get(id=request.POST.get('form-' + str(index) + '-id'))
photo.delete()
else:
photo = PhotoVilla(id_villa=villa, photo=f.cleaned_data.get('photo'))
d = PhotoVilla.objects.get(id=data[index].id)
d.photo = photo.photo
d.save()
return HttpResponseRedirect(villa.get_absolute_url())
else:
form = VillaEditForm(instance=villa)
formset = ImageFormset(queryset=PhotoVilla.objects.filter(id_villa=pk))
content = {
'form': form,
'villa': villa,
'formset': formset,
}
return render(request, 'registration/villa-update.html', content)
forms.py 文件:
class VillaEditForm(forms.ModelForm):
category = forms.ModelChoiceField(queryset=Category.objects.filter(typeWodden='v'))
class Meta:
model = Villa
fields = ["category", "code", "title", "duration", "thumbnail", "status", "service", "bed", "area"]
模板文件 html:
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
<div class="card-body">
<div class="form-group">
{{ form.title|as_crispy_field }}
</div>
{{ formset.management_form }}
{% for f in formset %}
<div style="background-color: #f2f4f4; margin: 5px; padding: 5px; width: 300px">{{ f.as_p }}</div>
{% endfor %}
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary float-right">درج</button>
</div>
</form>
请帮忙
解决方案
推荐阅读
- python - Python - 当行索引和列都是类别时数据帧值的散点图
- c++ - 插入运算符 (operator<<) 的这种递归重载是如何工作的?
- python - python ImageGrab.grabclipboard() 返回无
- python - 如何链接,然后“取消链接”嵌套列表?
- django - 如何在 django 中获取嵌套对象
- vb.net - vb.netread 在变量变暗中逐行读取
- flutter - 使用flutter中的syncfusion包在PDF中进行内部导航
- python - Python how to keep the XML comment exist after write a new value using Python?
- flutter - 在 null 上调用了 getter 键
- javascript - 更新前端的 ACF 字段设置