Sorry for my English. I have some data from another server, but I need to output this data like JSON.
if i print response in console:
{
'responseStatus': {
'status': [],
},
'modelYear': [
1981,
1982
]
}
but, if i return this response like HttpResponse i have an error
AttributeError: 'str' object has no attribute '_meta'
this my code:
data = serializers.serialize('json', response, ensure_ascii=False)
return HttpResponse(data, content_type="application/json")
UPD:
I tried with this:
from django.http import JsonResponse
def some_view(request):
...
return JsonResponse(response, safe=False)
but have error:
Object of type 'ModelYears' is not JSON serializable
UPD:
I did like this:
import json
from django.http import JsonResponse
def some_view(request):
...
return JsonResponse(json.loads(response))
but have error:
the JSON object must be str, bytes or bytearray, not 'ModelYears'
The Django docs says the following about the serializers framework:
Django’s serialization framework provides a mechanism for “translating” Django models into other formats.
The error indicates that your variable response is a string and not an Django model object. The string seems to be valid JSON so you could use JsonResponse:
import json
from django.http import JsonResponse
# View
return JsonResponse(json.loads(response))
Replace your code with following:
from django.http import JsonResponse
def some_view(request):
...
return JsonResponse(response)
Instead of serializing and sending it via httpresponse.
This works for python 3.6 and Django 2.0
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
import requests
#login_required()
def get_some_items(request):
headers = {"Authorization": "Token uydsajbkdn3kh2gj32k432hjgv4h32bhmf"}
host = "https://site/api/items"
response = requests.get(host, headers=headers)
result = JsonResponse(response.json())
return HttpResponse(result, content_type='application/json')
Related
I have made an DjangoRestApi and giving user input using postman(POST method).but the error is
TypeError: Object of type 'JSONDecodeError' is not JSON serializable
it is showing in django server where i am going wrong please help Thanks
views.py
import spacy
from django.shortcuts import render,HttpResponse
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from django.core import serializers
from django.conf import settings
import json
nlp = spacy.load('en_core_web_sm')
#api_view(["POST"])
def nounphrases(requestdata):
try:
text = json.loads(requestdata.body)
nounphrases = []
for word in (nlp((text))):
c = (word.lemma_)
nounphrases.append(c)
output = [{"nounphrases" : nounphrases }]
return JsonResponse(json.dumps(output))
except ValueError as e:
return Response(e,status.HTTP_400_BAD_REQUEST)
I am getting this error...
Object of type 'Settings' is not JSON serializable
Here is my code
from django.conf import settings
import json
def get_settings(request):
responce = settings.__dict__
return HttpResponse(json.dumps(responce),content_type='application/json')
django.conf.settings is not Json serializable, thought you can go throught and create dict() then give it to HttpResponse. Hope it helps!
import json
from django.http import HttpResponse
from django.conf import settings
def get_settings(request):
context = {}
for setting in dir(settings):
if setting.isupper():
context[setting] = getattr(settings, setting)
return HttpResponse(json.dumps(context, indent=4), content_type="application/json")
In django my view.py is
import json
from django.http import HttpResponse
from django.template import Template, Context
from django.shortcuts import render_to_response
def ajax(request):
obj =[dict(a = 1,b = 2)]
jsons=json.dumps(obj)
print jsons
return render_to_response("2.html", {"obj_as_json": jsons})
I want to display value of a and b that are JSON in my template 2.html. Please help me to write the code.
I don't understand the usage of View.
Why do you want to pass JSON object as a context value while Template Rendering ?
The standard is When you do a Ajax request its response should be a JSON response i.e mimetype=application/json.
So, You should render the template normally and Convert the result into JSON and return.
e.g:
def ajax(request):
obj = {
'response': render_to_string("2.html", {"a": 1, "b": 2})
}
return HttpResponse(json.dumps(obj), mimetype='application/json')
OR
you can create a JSONResponse class Similar to HttpResponse to make it generic . e.g.
class JSONResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JSONResponse, self).__init__(
content=json.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
and use like : return JSONResponse(obj)
This has been added by default in django 1.7: https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects
This is related to this question: Django return json and html depending on client python
I have a command line Python API for a Django app. When I access the app through the API it should return JSON and with a browser it should return HTML. I can use different URLs to access the different versions but how do I render the HTML template and JSON in the views.py with just one template?
To render the HTML I would use:
return render_to_response('sample/sample.html....')
But how would I do the same for JSON without putting a JSON template? (the content-type should be application/json instead of text/html)
What would determine the JSON and HTML outputs?
So in my views.py:
if something:
return render_to_response('html_template',.....)
else:
return HttpReponse(jsondata,mimetype='application/json')
I think the issue has gotten confused regarding what you want. I imagine you're not actually trying to put the HTML in the JSON response, but rather want to alternatively return either HTML or JSON.
First, you need to understand the core difference between the two. HTML is a presentational format. It deals more with how to display data than the data itself. JSON is the opposite. It's pure data -- basically a JavaScript representation of some Python (in this case) dataset you have. It serves as merely an interchange layer, allowing you to move data from one area of your app (the view) to another area of your app (your JavaScript) which normally don't have access to each other.
With that in mind, you don't "render" JSON, and there's no templates involved. You merely convert whatever data is in play (most likely pretty much what you're passing as the context to your template) to JSON. Which can be done via either Django's JSON library (simplejson), if it's freeform data, or its serialization framework, if it's a queryset.
simplejson
from django.utils import simplejson
some_data_to_dump = {
'some_var_1': 'foo',
'some_var_2': 'bar',
}
data = simplejson.dumps(some_data_to_dump)
Serialization
from django.core import serializers
foos = Foo.objects.all()
data = serializers.serialize('json', foos)
Either way, you then pass that data into the response:
return HttpResponse(data, content_type='application/json')
[Edit] In Django 1.6 and earlier, the code to return response was
return HttpResponse(data, mimetype='application/json')
[EDIT]: simplejson was remove from django, you can use:
import json
json.dumps({"foo": "bar"})
Or you can use the django.core.serializers as described above.
In Django 1.7 this is even easier with the built-in JsonResponse.
https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects
# import it
from django.http import JsonResponse
def my_view(request):
# do something with the your data
data = {}
# just return a JsonResponse
return JsonResponse(data)
In the case of the JSON response there is no template to be rendered. Templates are for generating HTML responses. The JSON is the HTTP response.
However, you can have HTML that is rendered from a template withing your JSON response.
html = render_to_string("some.html", some_dictionary)
serialized_data = simplejson.dumps({"html": html})
return HttpResponse(serialized_data, mimetype="application/json")
For rendering my models in JSON in django 1.9 I had to do the following in my views.py:
from django.core import serializers
from django.http import HttpResponse
from .models import Mymodel
def index(request):
objs = Mymodel.objects.all()
jsondata = serializers.serialize('json', objs)
return HttpResponse(jsondata, content_type='application/json')
It looks like the Django REST framework uses the HTTP accept header in a Request in order to automatically determine which renderer to use:
http://www.django-rest-framework.org/api-guide/renderers/
Using the HTTP accept header may provide an alternative source for your "if something".
You could also check the request accept content type as specified in the rfc. That way you can render by default HTML and where your client accept application/jason you can return json in your response without a template being required
from django.utils import simplejson
from django.core import serializers
def pagina_json(request):
misdatos = misdatos.objects.all()
data = serializers.serialize('json', misdatos)
return HttpResponse(data, mimetype='application/json')
Here's an example I needed for conditionally rendering json or html depending on the Request's Accept header
# myapp/views.py
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
from .models import Event
def event_index(request):
event_list = Event.objects.all()
if request.META['HTTP_ACCEPT'] == 'application/json':
response = serializers.serialize('json', event_list)
return HttpResponse(response, content_type='application/json')
else:
context = {'event_list': event_list}
return render(request, 'polls/event_list.html', context)
you can test this with curl or httpie
$ http localhost:8000/event/
$ http localhost:8000/event/ Accept:application/json
note I opted not to use JsonReponse as that would reserialize the model unnecessarily.
If you want to pass the result as a rendered template you have to load and render a template, pass the result of rendering it to the json.This could look like that:
from django.template import loader, RequestContext
#render the template
t=loader.get_template('sample/sample.html')
context=RequestContext()
html=t.render(context)
#create the json
result={'html_result':html)
json = simplejson.dumps(result)
return HttpResponse(json)
That way you can pass a rendered template as json to your client. This can be useful if you want to completely replace ie. a containing lots of different elements.
I am trying to set up a view to received a JSON notification from an API. I'm trying to figure out how to get the JSON data, and I currently have this as a starting point to see that the request is being properly received:
def api_response(request):
print request
return HttpResponse('')
I know the JSON object is there because in the print request it shows:
META:{'CONTENT_LENGTH': '178',
[Fri Sep 09 16:42:27 2011] [error] 'CONTENT_TYPE': 'application/json',
However, both of the POST and GET QueryDicts are empty. How would I set up a view to receive the JSON object so I can process it? Thank you.
This is how I did it:
def api_response(request):
try:
data=json.loads(request.raw_post_data)
label=data['label']
url=data['url']
print label, url
except:
print 'nope'
return HttpResponse('')
I'm going to post an answer to this since it is the first thing I found when I searched my question on google. I am using vanilla django version 3.2.9. I was struggling to retrieve data after making a post request with a json payload to a view. After searching for a while, I finally found the json in request.body.
Note: request.body is of type bytes, you'll have to decode it to utf-8, my_json_as_bytes.decode('utf-8')
or, if you want a dictionary, you can just use json.load(request.body) to decode directly.
On a function view, you can try this out.
dp = json.dumps(request.data)
contact = json.loads(dp)
print(contact['first_name'])
For Class-Based Views built Using Django-Rest-Framework,
you can use built-in JSONParser to get JSON data in request.data
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
class MyOveridingView(APIView):
parser_classes = [JSONParser]
class MyActualView(MyOveridingView):
def post(self, request, *args, **kwargs):
request_json = request.data
return JsonResponse(data=request_json, status=200)