1088π
I usually use a dictionary, not a list to return JSON content.
import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
Pre-Django 1.7 youβd return it like this:
return HttpResponse(json.dumps(response_data), content_type="application/json")
For Django 1.7+, use JsonResponse
as shown in this SO answer like so :
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
200π
New in django 1.7
you could use JsonResponse objects.
from the docs:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
- [Django]-Annotate a queryset with the average date difference? (django)
- [Django]-How to get superuser details in Django?
- [Django]-How to pass multiple values for a single URL parameter?
156π
I use this, it works fine.
from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Alternative:
from django.utils import simplejson
class JsonResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JsonResponse, self).__init__(
content=simplejson.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
- [Django]-Heroku, postgreSQL, django, comments, tastypie: No operator matches the given name and argument type(s). You might need to add explicit type casts
- [Django]-How to revert the last migration?
- [Django]-Django composite unique on multiple model fields
27π
Since Django 1.7 you have a standard JsonResponse thatβs exactly what you need:
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
You donβt even need to json.dump your array.
- [Django]-Django model constraint for related objects
- [Django]-Form with CheckboxSelectMultiple doesn't validate
- [Django]-Python Socket.IO client for sending broadcast messages to TornadIO2 server
25π
With Django Class-based views you can write:
from django.views import View
from django.http import JsonResponse
class JsonView(View):
def get(self, request):
return JsonResponse({'some': 'data'})
and with Django-Rest-Framework you can write:
from rest_framework.views import APIView
from rest_framework.response import Response
class JsonView(APIView):
def get(self, request):
return Response({'some': 'data'})
- [Django]-How to resize an ImageField image before saving it in python Django model
- [Django]-Jquery template tags conflict with Django template!
- [Django]-ModuleNotFoundError: No module named 'grp' on windows
20π
For those who use Django 1.7+
from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
- [Django]-How to use refresh token to obtain new access token on django-oauth-toolkit?
- [Django]-Django content-type : how do I get an object?
- [Django]-Django: Using F arguments in datetime.timedelta inside a query
18π
from django.http import HttpResponse
import json
class JsonResponse(HttpResponse):
def __init__(self, content={}, mimetype=None, status=None,
content_type='application/json'):
super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
status=status, content_type=content_type)
And in the view:
resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
- [Django]-Django β {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Change a form value before validation in Django form
- [Django]-Why am I getting this error in Django?
12π
Youβll want to use the django serializer to help with unicode stuff:
from django.core import serializers
json_serializer = serializers.get_serializer("json")()
response = json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
return HttpResponse(response, mimetype="application/json")
- [Django]-How to manually assign imagefield in Django
- [Django]-Django β how to unit test a post request using request.FILES
- [Django]-Best practices for getting the most testing coverage with Django/Python?
11π
Its very convenient with Django version 1.7 or higher as you have the JsonResponse class, which is a subclass of HttpResponse.
from django.http import JsonResponse
def profile(request):
data = {
'name': 'Raghav',
'location': 'India',
'is_active': False,
'count': 28
}
return JsonResponse(data)
For older versions of Django, you must use an HttpResponse object.
import json
from django.http import HttpResponse
def profile(request):
data = {
'name': 'Raghav',
'location': 'India',
'is_active': False,
'count': 28
}
dump = json.dumps(data)
return HttpResponse(dump, content_type='application/json')
- [Django]-How can I keep test data after Django tests complete?
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-Django: show the count of related objects in admin list_display
8π
How to use google app engine with ajax (json)?
Code Javascript with JQuery:
$.ajax({
url: '/ajax',
dataType : 'json',
cache: false,
success: function(data) {
alert('Load was performed.'+data.ajax_resp);
}
});
Code Python
class Ajax(webapp2.RequestHandler):
def get(self):
my_response = {'ajax_resp':'Hello, webapp World!'}
datos = json.dumps(my_response)
self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
self.response.out.write(datos)
- [Django]-Add rich text format functionality to django TextField
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
6π
First import this:
from django.http import HttpResponse
If you have the JSON already:
def your_method(request):
your_json = [{'key1': value, 'key2': value}]
return HttpResponse(your_json, 'application/json')
If you get the JSON from another HTTP request:
def your_method(request):
response = request.get('https://www.example.com/get/json')
return HttpResponse(response, 'application/json')
- [Django]-Django: sqlite for dev, mysql for prod?
- [Django]-Django model one foreign key to many tables
- [Django]-VueJS + Django Channels
5π
This is my preferred version using a class based view.
Simply subclass the basic View and override the get()-method.
import json
class MyJsonView(View):
def get(self, *args, **kwargs):
resp = {'my_key': 'my value',}
return HttpResponse(json.dumps(resp), mimetype="application/json" )
- [Django]-How do I deploy Django on AWS?
- [Django]-Django return file over HttpResponse β file is not served correctly
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'
5π
Django code views.py
:
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
HTML code view.html
:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/view/',
data: {
'fruit': selected
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{{data}}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
- [Django]-Django {% if forloop.first %} question
- [Django]-Pulling data to the template from an external database with django
- [Django]-Adding to the "constructor" of a django model
4π
This way the json contents can be downloaded as a file with a specific filename.
import json
from django.http import HttpResponse
def download_json(request):
data = {'some': 'information'}
# serialize data obj as a JSON stream
data = json.dumps(data)
response = HttpResponse(data, content_type='application/json charset=utf-8')
# add filename to response
response['Content-Disposition'] = 'attachment; filename="filename.json"'
return response
- [Django]-Django Background Task
- [Django]-Django manage.py runserver invalid syntax
- [Django]-Django-taggit β how do I display the tags related to each record
3π
Most of these answers are out of date. JsonResponse is not recommended because it escapes the characters, which is usually undesired. Hereβs what I use:
views.py (returns HTML)
from django.shortcuts import render
from django.core import serializers
def your_view(request):
data = serializers.serialize('json', YourModel.objects.all())
context = {"data":data}
return render(request, "your_view.html", context)
views.py (returns JSON)
from django.core import serializers
from django.http import HttpResponse
def your_view(request):
data = serializers.serialize('json', YourModel.objects.all())
return HttpResponse(data, content_type='application/json')
Bonus for Vue Users
If you want to bring your Django Queryset into Vue, you can do the following.
template.html
<div id="dataJson" style="display:none">
{{ data }}
</div>
<script>
let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
var app = new Vue({
el: '#app',
data: {
yourVariable: dataParsed,
},
})
</script>
- [Django]-Celery discover tasks in files with other filenames
- [Django]-Django development server reload takes too long
- [Django]-Printing Objects in Django
1π
In View use this:
form.field.errors|striptags
for getting validation messages without html
- [Django]-How do Django models work?
- [Django]-How to check if ManyToMany field is not empty?
- [Django]-Specifying limit and offset in Django QuerySet wont work
0π
def your_view(request):
response = {'key': "value"}
return JsonResponse(json.dumps(response), content_type="application/json",safe=False)
#Specify the content_type and use json.dump() son as the content not to be sent as object
- [Django]-How to resize an ImageField image before saving it in python Django model
- [Django]-How to use regex in django query
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?