What are the best practices to use AngularJS with Django
angularjs, django, rest
Solution
There are ways of powering your client-side templates from Django templates for interesting optimizations; however, given the similarities between Django and AngularJS's template languages, it's almost never worth the effort here. I will pair static serving of AngularJS with the Django REST Framework for most projects of this sort.
My `urls.py` order of operations is almost always the Django REST Framework URLs first (written as strictly as possible), followed by a generic pattern that points everything else to my base AngularJS application template in my `STATIC_ROOT` dir for local testing/dev scenarios:
if settings.DEBUG:
urlpatterns += patterns('django.contrib.staticfiles.views',
url(r'', 'serve', {
'document_root': settings.STATIC_ROOT,
'path': '/base.html'}
),
)
By pointing all of the unmatched requests to the same app/template, you can start using the history-hack method of URLs and routing if you'd prefer that to hashtags. If you plan only to stick to hashtags, your final URL match could be stricter (for example matching `/` (URL root) with `r'^$'`).
In production, I'll use a reverse proxy or slow-clients HTTP server like nginx to serve the AngularJS (static) content, proxying the requests for REST services to the Django WSGI app.
For communicating with the Django REST Framework, I prefer to have class-like JS objects to marshal the data to and from the AngularJS app and the Django REST Framework. For this, I use angular-django-rest-resource to generate classes that represent the Django model classes I'm exposing in the REST Framework views.
For maximum flexibility in the queries angular-django-rest-resource can make for resources, I will have the django-filter backend installed for the REST Framework as described here. This allows the JS resources to request the Django objects constrained by parameters (e.g. `/polls/?author=345&finished=1`).
If you're deploying the Django and REST operations on a separate domain of servers from whence the AngularJS main template is served (for example, if you're using a third-party CDN on a different Internet domain for the HTML), then it's important to allow cross-domain requests to those resources. For this, I recommend the django-cors-headers middleware.
I hope this is helpful. It's not the best practice set, but it's one that has worked for me.
Problem
I am about to start a project with AngularJS for the client side and Django for the server side. What are the best practices to make them work like best friends (static files,auth, deployment, etc.)