Opened 12 years ago

Closed 12 years ago

Last modified 12 years ago

#20270 closed Bug (fixed)

bug in ajax example

Reported by: tejinderss@… Owned by: nobody
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: bmispelon@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/#ajax-example

This example does not work with CreateView or UpdateView because the form_valid overriding never saves the form and neither does it call its super class which does. So in order for CreateView to create new object, we would either have to add:

def form_valid(self, form):

if self.request.is_ajax():

self.object = form.save()
data = {

'pk': form.instance.pk,

}
return self.render_to_json_response(data)

else:

return super(AjaxableResponseMixin, self).form_valid(form)

Or somehow call the super form_valid and then return the HttpResponse.

Change History (6)

comment:1 by Baptiste Mispelon, 12 years ago

Cc: bmispelon@… added
Easy pickings: set
Triage Stage: UnreviewedAccepted

I like the second option better, because it would make this mixin more composable with other ones (in general, I find that CBV mixins should always call the super(...) implementation of the method they extend).

I'm not too sure how to achieve this elegantly though. Maybe something like that:

def form_valid(self, form):
    response = super(AjaxableResponseMixin, self).form_valid(form)
    if self.request.is_ajax():
        json_context = {'pk': self.object.pk}
        return self.render_to_json(json_context)
    return response

comment:2 by anonymous, 12 years ago

With the second approach there must be defined "success_url" in the subclass otherwise it errors out. But with json response view i don't think success_url should be a required parameter. Or we can set bogus success_url in this mixin if the request type is ajax?

comment:3 by anonymous, 12 years ago

Nevermind we do need success_url for non Ajax response anyway.

comment:4 by Baptiste Mispelon, 12 years ago

Has patch: set

Here's a pull request based on my initial comment: https://github.com/django/django/pull/1026

comment:5 by Claude Paroz <claude@…>, 12 years ago

Resolution: fixed
Status: newclosed

In 73c26f0c95e83582e933e0ef2f71a013f7a9740e:

Fixed #20270 -- Fixed error in AjaxResponseMixin documentation

comment:6 by Claude Paroz <claude@…>, 12 years ago

In 6bb8df0a982bb394f2cf33cfc9d9d71589515801:

[1.5.x] Fixed #20270 -- Fixed error in AjaxResponseMixin documentation

Backport of 73c26f0c95 from master.

Note: See TracTickets for help on using tickets.
Back to Top