3

this should be a fairly easy one, but I am really struggling to figure it out by my self.

I am doing a real estate app and I need my users to be able to upload their images of houses. Each image is related to a House and each House is related to a User.

The way it is it works, but if the user submits an empty form with my formset the whole thing breaks, because it registers a non existent image to a User and a House. How can I prevent that?

Heres my View:

def photos_formset(request, *args, **kwargs):
    pk = kwargs['pk']
    ImovelPhotosModelFormset = modelformset_factory(ImovelPhotos, form=ImovelPhotosForm)
    formset = ImovelPhotosModelFormset(
            request.POST or None, request.FILES or None,
            queryset = Imovel.objects.get(pk=pk).imovelphotos_set.all(),
        )
    if formset.is_valid():
        for form in formset:
            if not request.FILES:
                break
            if form.is_valid():
                obj = form.save(commit=False)
                obj.user = request.user
                obj.imovel = Imovel.objects.get(pk=pk)
                obj.save()
        return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk))

    context = {
        "formset": formset,
    }
    return render(request, "imovel_photos.html", context)

The thing that looked more like a potential answer was this, but it didn't work, if I do this nothing happens:

if form.is_valid() and not form.empty_permitted:
4

1 回答 1

6

I had to identify which forms were coming with with an empty cleaned_data. The following code did the trick.

if formset.is_valid():
        if request.FILES:
            for form in formset:
                if form.is_valid():
                    if form.cleaned_data != {}:
                        obj = form.save(commit=False)
                        obj.user = request.user
                        obj.imovel = Imovel.objects.get(pk=pk)
                        obj.save()
        return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk))
于 2017-03-30T05:29:39.227 回答