I'm rewriting an application of mine to user CBV instead of functions. I
stuck at a point where I wanted to return a JSON response inside the
form_invalid function but always got a ''view didn't return an
HttpResponse object''-error. Therefore I thought to myself to try it
inside the post function where it suddenly worked.
To spare us words, here's my setup (simplified for better readability):
== urls.py: ==
url( r'^plans/$', login_required( MainView.as_view(
context_object_name='services',
model = Service,
template_name = 'plans.html',
paginate_by = 5,
form_class = addServiceForm,
success_url = reverse_lazy('plans')) ),
name="plans" ),
== views.py: ==
class MainView(ListView, FormMixin):
# NOTICE: I put this only here for completion
def get(self, request, *args, **kwargs):
view = DefView.as_view(
context_object_name=self.context_object_name, model=self.model,
queryset=self.queryset, template_name=self.template_name,
paginate_by=self.paginate_by, form_class=self.form_class,
success_url=self.success_url )
return view(request, *args, **kwargs)
# NOTICE: here's our patient
def post(self, request, *args, **kwargs):
view = SubTestView.as_view( template_name=self.template_name,
form_class=self.form_class, success_url=self.success_url )
#'''This one does NOT work'''
class SubTestView(FormView):
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
self.form_invalid(form)
def form_invalid(self, form):
data = {
'pk': "Test_PK",
}
return self.render_to_json_response(data)
#'''This one DOES work'''
class SubTestView(FormView):
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
data = {
'pk': "Test_PK",
}
return self.render_to_json_response(data)
Well, regarding the code I don't really see any difference. Am I doing
something wrong or is this just a bug?
Tested with following setups:
OSX 10.9.2, Python 2.7/3.3/3.4, Django 1.6.2/1.5
Regards
marius
--
Ticket URL: <https://code.djangoproject.com/ticket/22469>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* status: new => closed
* needs_better_patch: => 0
* resolution: => needsinfo
* needs_tests: => 0
* needs_docs: => 0
Comment:
I'm a bit skeptical that there is a bug in `form_invalid`. Try to make and
attach to this ticket a sample project which demonstrates this issue.
--
Ticket URL: <https://code.djangoproject.com/ticket/22469#comment:1>