diff --git a/docs/topics/class-based-views/generic-editing.txt b/docs/topics/class-based-views/generic-editing.txt index 30e2dac787..82761a1985 100644 --- a/docs/topics/class-based-views/generic-editing.txt +++ b/docs/topics/class-based-views/generic-editing.txt @@ -218,9 +218,7 @@ AJAX example Here is a simple example showing how you might go about implementing a form that works for AJAX requests as well as 'normal' form POSTs:: - import json - - from django.http import HttpResponse + from django.http import JsonResponse from django.views.generic.edit import CreateView from myapp.models import Author @@ -229,15 +227,10 @@ works for AJAX requests as well as 'normal' form POSTs:: Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ - 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 form_invalid(self, form): response = super(AjaxableResponseMixin, self).form_invalid(form) if self.request.is_ajax(): - return self.render_to_json_response(form.errors, status=400) + return JsonResponse(form.errors, status=400) else: return response @@ -250,7 +243,7 @@ works for AJAX requests as well as 'normal' form POSTs:: data = { 'pk': self.object.pk, } - return self.render_to_json_response(data) + return JsonResponse(data) else: return response diff --git a/docs/topics/class-based-views/mixins.txt b/docs/topics/class-based-views/mixins.txt index f0bacca6c1..0f05102f0c 100644 --- a/docs/topics/class-based-views/mixins.txt +++ b/docs/topics/class-based-views/mixins.txt @@ -608,8 +608,7 @@ conversion to JSON once. For example, a simple JSON mixin might look something like this:: - import json - from django.http import HttpResponse + from django.http import JsonResponse class JSONResponseMixin(object): """ @@ -619,19 +618,20 @@ For example, a simple JSON mixin might look something like this:: """ Returns a JSON response, transforming 'context' to make the payload. """ - return HttpResponse( - self.convert_context_to_json(context), - content_type='application/json', + return JsonResponse( + self.get_data(context), **response_kwargs ) - def convert_context_to_json(self, context): - "Convert the context dictionary into a JSON object" + def get_data(self, context): + """ + Returns an object that will be serialized as JSON by json.dumps(). + """ # Note: This is *EXTREMELY* naive; in reality, you'll need # to do much more complex handling to ensure that arbitrary # objects -- such as Django model instances or querysets # -- can be serialized as JSON. - return json.dumps(context) + return context .. note::