首页 > 解决方案 > 当我尝试在 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>

请帮忙

标签: django

解决方案


推荐阅读