AndrewIngram / django-extra-views

Django's class-based generic views are awesome, let's have more of them.
MIT License
1.38k stars 172 forks source link

Ajax response #218

Closed stephendwolff closed 3 years ago

stephendwolff commented 4 years ago

I have been trying to override the form_invalid of my CBV to return JSON which has a signature:

class ProfileView(LoginRequiredMixin, UpdateWithInlinesView):

I have a mixin which i use for standard UpdateView CBVs but it isn't being called with the extra_views version. All the mixin ads is a method like:

    def form_invalid(self, form):
        response = super(AjaxResponseMixin, self).form_invalid(form, inlines)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

I've tried adding the method directly to my superclass, but it isn't being used - possibly because with the inlines there is an extra parameter: 'inlines' in the form_invalid.

sdolemelipone commented 3 years ago

Hi @stephendwolff, the method isn't being used because ProcessFormWithInlinesView calls forms_invalid() and not form_invalid(). Replace your code with something like the below and it should work:

def forms_invalid(self, form, inlines):
    if self.request.is_ajax():
        # here's a way you could get the errors as a dictionary
        errors = {"form": form.errors, "inlines": [{"non_form_errors":i.non_form_errors, "form_errors": i.errors} for i in inlines]}
        return JsonResponse(errors, status=400)
    else:
        return super(AjaxResponseMixin, self).forms_invalid(form, inlines)