#22591 closed New feature (wontfix)
Changing of HTTP status code in form_invalid()
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Forms | Version: | dev |
Severity: | Normal | Keywords: | forms |
Cc: | Adam Wróbel | Triage Stage: | Unreviewed |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
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 https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/#ajax-example, 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/edit.py:
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 (4)
comment:1 by , 11 years ago
comment:2 by , 10 years ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
comment:3 by , 5 years ago
http status code "200" on POST and invalid data is a bit strange. Django does this since ages, nevertheless I think there should at least be simple way to specify a different http status code.
Maybe give FormMixin an overwritable attribute http_status_on_invalid. This
should default to the old "200", but would allow subclasses to overwrite it easily without coding.
comment:4 by , 4 years ago
Cc: | added |
---|
The main issue I see with this is that you're hijacking
kwargs
forrender_to_response()
. It seems equally likely that someone could propose passing them toget_context_data()
. To achieve what you're after, I wonder if it would be better to overriderender_to_response()
with something like: