Opened 5 years ago

Closed 5 years ago

#22591 closed New feature (wontfix)

Changing of HTTP status code in form_invalid()

Reported by: kevmo314@… Owned by: nobody
Component: Forms Version: master
Severity: Normal Keywords: forms
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no


Would it be possible to permit the changing of status codes on form_invalid? We had a form where we wanted to return a 400 status code when a validation error occurs, but by default Django spits out a 200 error code. In other words, following the example at, we'd like to return a 400 on a non-ajax request as well.

Here's the change I'd like to propose. On line 78 of django/views/generic/

    def form_invalid(self, form, **kwargs):
        If the form is invalid, re-render the context data with the
        data-filled form and errors.
        return self.render_to_response(self.get_context_data(form=form), **kwargs)

This would permit doing something like this:

response = super(AjaxableResponseMixin, self).form_invalid(form, status=400)

Alternatively, a failure status code property may be more intuitive to developers, but I think the above permits a bit more flexibility in terms of modifying other attributes of the response as well.

Change History (2)

comment:1 Changed 5 years ago by Tim Graham

The main issue I see with this is that you're hijacking kwargs for render_to_response(). It seems equally likely that someone could propose passing them to get_context_data(). To achieve what you're after, I wonder if it would be better to override render_to_response() with something like:

form = context.get('form')
if form and not form.is_valid():
   response_kwargs['status'] = 400
super().render_to_response(context, **response_kwargs)

comment:2 Changed 5 years ago by Tim Graham

Resolution: wontfix
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top