mirror of
https://github.com/django/django.git
synced 2024-12-01 15:42:04 +01:00
Used JsonResponse in CBV examples.
Thanks Hiroki Kiyohara and Tim Graham for the reviews.
This commit is contained in:
parent
76f2f58a18
commit
7579080899
@ -217,9 +217,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
|
||||
|
||||
@ -228,15 +226,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
|
||||
|
||||
@ -249,7 +242,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
|
||||
|
||||
|
@ -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::
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user