I'd like to take advantage of all the field validation that comes with ModelForm and the convenience of handling related objects that comes with inlineformset_factory however I'd like to be able to post JSON data instead of using forms on my site.
In the past I've been using hidden forms and then serializing the form data and sending that to the server for AJAX like communication.
I'd prefer to do this in a less hacky way - ie. somehow co-opt forms to accept JSON data in a nice way.
Any suggestions/ examples?
Try loading the data via:
import json
data_dict = json.loads(data_json)
and then creating a new instance of the factory via
YourFactory(**data_dict)
Related
I can get data in JSON format, using a view and url by calling an AJAX function from JQuery. Which only needs to create a view and a url to access it. But is rest_framework to do the same thing I need to create serializer, views and a url to do the same. So is it good to use AJAXX in these cases or I need to use rest_framework every time.
Thanks.
Your question is not clear, From my understanding you want to know Why Django rest framework instead of JSONResponse?
JSONResponse:
JSONResponse will simply convert your model object to json response. You have restriction in formats and it's not efficient method when u have large dataset.
For more reference refer here
DRF:
Browsable API.
Serialization that supports both ORM and non-ORM data sources.
You don't need to write all the CRUD methods everytime.
The main advantage to use DRF is ModelViewset and Serialization. With the use of serializer you can access Related data(Foreign key & Many-to-Many) easily.
From my Opinion, if you have extensive API requirements, you can use the Django rest framework otherwise don't choose that.
Check this reference and decide based on your requirements.
https://medium.com/profil-software-blog/10-things-you-need-to-know-to-effectively-use-django-rest-framework-7db7728910e0
https://medium.com/crowdbotics/how-to-write-an-api-in-3-lines-of-code-with-django-rest-framework-59b0971edfa4
I had one business requirement to be implemented lately which required me to just fetch the data and render the response.
So some API endpoint would return a response as: [{"id" :1,"name":"first"} ,{"id" :2,"name":"second":}]
Can I just render this data by constructing a list of dictionaries which can be populated with various ORM queries instead of rendering the response through a serializer?
Would it be an efficient solution in case I won't be using this serializer ever for POST request?
It is fine to have Django Rest Framework without serializer.
But best practice would be using Serializer.
Using Serializer you can control the input and out of the data.
You can validate Data. You can serializer and deserializer the data. Much more than that. Think Serializer as Form
From the Docs
Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it will take
some serious design work.
— Russell Keith-Magee, Django users group
I need to built an "API". Using django restframework. API has to support multiple platforms like mobile apps, webapps.
API will be used as a backend which will store all information. But my problem is how do I access users information using API. I mean normally django has user model. And we access user related stuff using request.user. But how do I access request.user information using API. Please pardon me for asking such question. But as I am new to developing API for Mobile apps. I am facing difficulty.
I think the easiest way to think about it, is that Django Rest Framework will (normally) return or process JSON data, rather than an HTML page / HTML form data.
Your models stay the same.
If you use Django's ModelForms then DRF's ModelSerialzers are very similar in use.
Likewise, using Django's class based generic views, are very similar to DRF's generic views are very similar - except rather than processing POST data from an HTML forms, they will receive JSON data. The generic views cover the same things - create via POST, update via PUT, delete via DELETE.
Like I say the main difference is that you will be dealing with JSON in place of HTML.
(You could easily use bog standard Django views without the rest-framework and return or process JSON. DRF takes a fair bit of the boilerplate code out of the process).
My case is basic: I want to send urls of thumbnails to the client within responses to AJAX requests. I have custom image fields that deserialize base64 encoded images from the client and sorl_thumbnail as thumbnail engine. In my views I want to instantiate deserializer with arbitrary options for thumbnailer.
What is a common techniques for that in Django REST framework?
upd
The main problem is how to pass arguments about dimensions, format, quality, etc, to serializer? In one place I might need small thumbnail of the picture, in other bigger thumbnail.
Now I see two approaches:
- Make a factory which will produce serializer with given options for thumbnail-fields
- Send thumbnail options within AJAX requests and make serializer able to read and follow them.
There are lots of ways you could go about this, depending on a lot of information you don't give, but, perhaps look into using a SerializerMethodField in your serializer.
The basic idea would be to create a method that is able to return the appropriate URL for the thumbnail given the object instance and bind the SerializerMethodField to that.
By default DRF's GenericViews pass the request through to serializers via the context parameter. This enables you to access the request with such as request = self.context.get('request', None). From there you can read the thumbnail options as you suggest.
Hopefully that's enough to get you started.
What is the proper way to post json to Django? I have tried to use views, but I am not certain how to handle csrf. Is there another way to bypass views and simply accept a post of json?
Views are what handle the post data. There is no concept of "bypass views" because that is where the work of processing a request is done.
This is probably what your are looking for:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
This shows you how to handle csrf tokens with ajax (namely by using cookies).
I also might suggest you slow down and try to work through the tutorial found here:
https://docs.djangoproject.com/en/dev/intro/tutorial01/
You will likely have an easier time with django if you undertstand how the pieces (Models, Views, Templates, urls, Forms, etc) fit together.
Since you've added that these are API calls the simplest thing to do would be to mark these views as csrf_exempt. Additionally, as you might guess creating an API from models is a common task (I'm assuming that your API maps to models as that's the common case and you haven't specified) you may want to not reinvent the wheel and instead use piston or tastypie to make this easier on you: http://djangopackages.com/grids/g/api/
Use the #csrf_exempt decorator on any API views.