4

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:
1
  • 1
    You might want to draw inspiration from Django itself.
    – x-yuri
    Commented Mar 26, 2020 at 22:29

1 Answer 1

7

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))

Not the answer you're looking for? Browse other questions tagged or ask your own question.