How to post json to Django - django

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.

Related

How does viewset aligns with rest methods

I am relatively new to DRF, but found viewsets an amazing abstraction technique for writing RESTful API. I am having a hard time correlating Viewsets with REST methods though. Let's say I have a viewset for Userprofiles and somebody new creates a profile on client.
Should this send a PUT or a POST ?
Which url should this request go to, http://user or http://user/new_id ?
If I want this profile only accessible to the user or admin(all CRUD operations), then where should I handle the code for making it inaccessible to others ?
Should I create a new permission ? If yes, should I handle rest methods in has_permission/has_object_permission ?
I have gone through the tutorial, and know how permissions/mixins works, but I am not able to connect these dots here.
1/ In general, POST is for creating new, PUT is for updating. See the docs on the SimpleRouter to show how the various types of Http methods align with various actions in your Django backend.
2/ You'll find that different situations call for different routing methods. If yours is standard, you may want to use a SimpleRouter like the example above. In that case, creating a new user would be a POST request to /user/ and updating a user would be a PUT request to /user/{{user_id}}/.
3/ To limit access to various API methods, you want to use Permissions. It's possible that you could use one of DRF's Custom Permissions. I've found that in general, if you want only the user to access his/her own profile, it's easier to either use conditional logic within a view (i.e., return a DRF PermissionDenied exception in the view logic if the request.user.pk is not the pk of that REST url. More often than not, I've used the UserPassesTestMixin from Django Braces, that works pretty well to filter user permissions.
4/ I guess the Django Braces mixin above answers this question. You should include a test_func method if you're using Django Braces that returns True if you want to grant the user access, and False otherwise.
Hope this helps! I agree that these are difficult parts of DRF and perhaps some of these could more effectively get incorporated into the source. Good luck!

how to use django restframework as a backend for mobile apps

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).

django class-based views for handling AJAX responses

I was thinking about writing my own class-based views to consistently handle AJAX GET and AJAX POST (for posting form, which might return validation errors). Before I do so, I want to make sure I am not reinventing the wheel. Are there modules/apps out there already serving the said purpose?
In my projects, I use the django-dajax and django-dajaxice packages available in the PyPI database to handle AJAX related flow.
In my opinion, they created a very easy and eficient API to get the job done.
You can find out more about them following these links.
http://pypi.python.org/pypi/django-dajax
http://pypi.python.org/pypi/django-dajaxice

Is it hacky to manually construct JSON and manually handle GET, POST instead of using a proper RESTful API for AJAX functionality?

I started building a Django app, but this probably applies to other frameworks as well. In Backbone.js methods that call the server (fetch(), create(), destroy(), etc.), should you be using a proper RESTful API such as one provided by Tastypie or Django-Piston? I've founded it easier and more flexible to just construct the JSON in my Django Views, which are mapped to some URLs that Backbone.js can use. Then again, I'm probably not leveraging Tastypie/Django-Piston functionality to the fullest.
I'm not ready to make a full-fledged RESTful API for my app yet. I simply would like to use some of the AJAXy functionality that Backbone.js supports.
Pros/Cons of doing this?
Remember, REST does not equal JSON. If I require your representation in text/html, you should be able to provide me with that, or else throw a 415.
A better solution, then you are currently using, is to use the middleware functionality that Django provides. Whatever your view replies, use Djangos middleware functionality for the response to encode into JSON, XML or whatever.
I personally prefer defining my own ajax views and json objects. Using some already apis developed may be or may not be of much use. Some don't exactly fulfill the requirements some may have features which are redundant (And I don't like a code to be present which is not being used).
Also writing ajax functionality is not that difficult either. The inbuilt serializers / request.is_ajax features are there for your help.
Some examples for ajax implementation with django/jquery: http://webcloud.se/log/AJAX-in-Django-with-jQuery/ (You most probably have seen it already)

Django and Restful APIs

I have been struggling with choosing a methodology for creating a RESTful API with Django. None of the approaches I've tried seem to be the "silver" bullet. WAPI from http://fi.am is probably the closest to what I would like to accomplish, however I am not sure if it is acceptable in a true RESTful API to have parameters that are resource identifiers be in the querystring instead of in a "clean" URL format. Any suggestions for modifying WAPIs RestBinding.PATTERN to "clean" up the URLs? Another option I've explored is Django-Rest-Interface. However this framework seems to violate one of the most important pieces I need, and that is to include the full resource URL for references to other resources (see http://jacobian.org/writing/rest-worst-practices/ Improper Use of Links). The final option is to use django-multiresponse and basically do it the long way.
Please offer me your best advice, especially people that have dealt with this decision.
For Django, besides tastypie and piston, django-rest-framework is a promising one worth mentioning. I've already migrated one of my projects on it smoothly.
Django REST framework is a lightweight REST framework for Django, that
aims to make it easy to build well-connected, self-describing RESTful
Web APIs.
Quick example:
from django.conf.urls.defaults import patterns, url
from djangorestframework.resources import ModelResource
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
from myapp.models import MyModel
class MyResource(ModelResource):
model = MyModel
urlpatterns = patterns('',
url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
url(r'^(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
)
Take the example from the official site, all above codes provide api, self explained documentation (like soap based webservice) and even sandboxing for testing. Very convenient.
Links:
http://django-rest-framework.org/
I believe the recently released django-piston is now the best solution for creating a proper REST interface in Django. django-piston
Note: django-piston seems to no longer be maintained (see comments below)
django-tastypie is a good way to do it, their slogan: "Creating delicious APIs for Django apps since 2010" is pretty comforting ;)
You could take look at django-dynamicresponse, which is a lightweight framework for adding REST API with JSON to your Django applications.
It requires minimal changes to add API support to existing Django apps, and makes it straight-forward to build-in API from the start in new projects.
Basically, it includes middleware support for parsing JSON into request.POST, in addition to serializing the returned context to JSON or rendering a template/redirecting conditionally based on the request type.
This approach differs from other frameworks (such as django-piston) in that you do not need to create separate handlers for API requests. You can also reuse your existing view logic, and keep using form validation etc. like normal views.
I don't know if this project can be useful for you, but sending a link can hardly hurt. Take a look at django-apibuilder , available from http://opensource.washingtontimes.com/projects/django-apibuilder/ . Perhaps it can be useful?
/Jesper
Have a look at this RestifyDjango.
Somewhat related are Django XML-RPC and JSON-RPC.
https://github.com/RueLaLa/savory-pie
Savory Pie is a REST framework that supports django.
I would suggest you look into Django Rest Framework (DRF), play around with this and see if it suits your requirements. The reason I recommend DRF is because it makes making the API views really simple with the use of GenericAPIView classes, Mixin Classes and Mixed in Generic views. You can easily make use of tried and tested design patterns for making your API endpoints as well as keeping your code base neat and concise. You also DRY when writing your code which is always great. Your API views are literally 2-3 lines long.
You can checkout this tutorial http://programmathics.com/programming/python/django-rest-framework-setup/ that begins from setting up your environment to going through the different ways to make your RESTful API using the django rest framework.
Disclaimer: I am the creator of that website.