I'm using django 1.8 rest api as below.
#api_view(['GET', 'POST'])
#authentication_classes((TokenAuthentication, SessionAuthentication, BasicAuthentication))
#permission_classes((IsAuthenticated,))
#staff_member_required
def api(request):
print request.data
The problem with this is that it retrieves all parameters as string so I have to convert numbers and boolean manually.
I tried using:
print json.loads(request.body)
but apparently django rest framework reads from the data stream which causes this error:
Error: RawPostDataException: You cannot access body after reading from request's data stream
I also tried
json.loads(request.stream.body)
because the documentation says stream should work.
Is there a way I can retrieve the request post data with the appropriate types?
Note that I'm using ajax to send the data with JSON.stringify.
You want to use serializers in DRF. They will allow you to convert model instances to native Python datatypes which can be translated into JSON and vice versa. You can also deserialize which will convert those JSON strings to complex types.
Read more about serializers here
Related
I would like to know if it's possible to nest serializers without using the rest framework.
I was reading this question and I would like to do something similar but I am not allowed to use the rest framework.
Is it possible to serialize models with foreign keys using a similar approach (nesting) without using the rest framework?
At the moment I am serializing json like this:
data = serialize("json", myModelObject, fields=('id', 'foreignKeyField'), cls=DatetimeJSONEncoder)
And I would like to do something like this:
data = serialize("json", myModelObject, fields=('id', 'foreignKeyField.some_value'), cls=DatetimeJSONEncoder)
first make sure your view inherit from JSONResponseMixin
class JSONResponseMixin(object):
def render_to_json_response(self, context, **response_kwargs):
return JsonResponse(self.get_data(context), **response_kwargs)
def get_data(self, context):
return context
how about this :
Broaden your query values to include foreignKeyField.some_value
convert the queryset to list
return the json list as response for your ajax request
access your response as json array in ajax success
results = MyModel.objects.filte(my_filter).values("field_1",
"field_2",
"field_n",
"foreignKeyfield__field_11",
"foreignKeyfield__field_22")
results_list = json.dumps(results)
return JsonResponse(results_list)
it depends on your frontend technologie , try to output the reponse and parse with joy
let me know in the comments section if you need more details
I'm working on creating a RESTAPI using DRF(Django Rest Framework). API just receives the users twitter handle and returns his twitter data.
Here, I'm not using model here because it's not required.
Should I use a serializer here? If so why? Now I'm able to return the data without using a serializer.
Moreover, My API is not web-browsable. How should I make it web-browsable: which is one of the best features of DRF.
Edit:1
I'm using Functions in Views.
#api_view(['GET'])
#csrf_exempt
def getdetails(request):
call the twitter api
receive the data
return HttpResponse(JsonResponse( {'data': {'twitter_id':id,'tweets':count,'Followers':followers,'following':count_follow}}))
In the browser I'm just seeing JSON data like this.
{"data": {"twitter_id": 352525, "tweets": 121, "Followers": 1008, "following": 281}}
You can use Serializer for the result
class SampleSerializer(serializers.Serializer):
field1 = serializers.CharField()
field2 = serializers.IntegerField()
# ... other fields
Usage
my_data = {
"field1": "my sample",
"field2": 123456
}
my_serializer = SampleSerializer(data=my_data)
my_serializer.is_valid(True)
data = my_serializer.data
You'll get serialized data in data variable (you can use my_serializer.data directly)
Should I use a serializer here?
It's up to you, because if you wish to show the response JSON without any modification from the Twitter API, you can go without DRF serializer. And If you wish to do some formatting on the JSON, my answer will help you
My API is not web-browsable. How should I make it web-browsable?
Maybe you followed wrong procedure. Anyway we can't say more on this thing without seeing your code snippets
Update-1
from rest_framework.response import Response
#api_view(['GET'])
#csrf_exempt
def getdetails(request):
call the twitter api
twitter_api = get_response_from_twitter() # Json response
return Response(data=twitter_api)
I use Django Channels to retrieve the data from Django Restful (DRF) serializer (I use channels because database is large and if I call for the data directly it results in a server timeout).
What I struggle with (perhaps I don't understand something about how DRF works), is how to get the html representation of Browsable API. So basically what I need to do is to send back as html a response based on BrowsableAPIRenderer when a person connects via WebSocket:
def connect(self, message, **kwargs):
myobj = MyObj.objects.filter(code=self.obj_code)
serializer = MyObjSerializer(myobj, many=True)
self.send(Response(serializer.data))
But that results in an error Response is not JSON serializable.
Im using DJango REST framework to write my web service layer in which I want to read request payload from the request (POST). I tried the following code but I get empty set
#api_view(['POST'])
def login(request):
print request.POST
Content Type is JSON. I tried to pass data from REST Client Tool. Still am able to read header values but only Payload is not coming out.
You should use request.DATA instead of request.POST to retrieve json data.
request.DATA has been deprecated in favor of request.data since version 3.0, and has been fully removed as of version 3.2.
is there a way i can pass json format data through django HttpResponse. I am trying to call the view through prototype ajax and return json format data.
Thanks
You could do something like this inside your app views.py
import json
def ajax_handler(req, your_parameter):
json_response = json.dumps(convert_data_to_json)
return HttpResponse(json_response,mimetype='application/json')
Building on Lombo's answer, you might want to utilize the request.is_ajax() method. This checks the HTTP_X_REQUESTED_WITH header is XmlHttpRequest.
This is a good way to avoid sending a json response to a regular GET - which I guess at worst is just confusing to your users, but also lets you use the same view for ajax vs. non-ajax requests. This approach makes it easier to build apps that degrade gracefully.
For example:
def your_view(request):
data_dict = # get some data
if request.is_ajax():
# return json data for ajax request
return HttpResponse(json.dumps(data_dict),mimetype='application/json')
# return a new page otherwise
return render_to_response("your_template.html", data_dict)
This approach works particularly well for form processing also.