AngularJS plus Django: A match made in heaven

I've just finished watching "AngularJS plus Django: A match made in heaven" DjangoCon US 2014 talk by Nina Zakharenko (https://www.youtube.com/watch?v=vWJorwEQWLk">Video | http://www.slideshare.net/nnja/djangocon-2014-angular-django">Slides) and it was quite helpful. Since I'm working with API's and mobile / angular apps a lot, I just made some helpful Django + AngularJS related notes that came out of this talk. Maybe these will be helpful for myself and, maybe, you :)

1) Example model

1
2
3
4
5
6
  1. class Tweet(models.Model):
  2. user = models.ForeignKey(User)
  3. text = models.CharField(max_length=140)
  4. timestamp = models.DateTimeField(auto_now_add=True)
  5. class Meta:
  6. ordering = ['-timestamp']

2) Endpoints

/api/users/ /api/tweets/ /api/users/:id /api/tweets/:id

3) Necessary config for AngularJS

1
2
3
4
5
6
7
8
9
  1. // Change tag symbols, replace {{ }} with [[ ]]
  2. $interpolateProvider.startSymbol('[[').endSymbol(']]');
  3. // Add CSRF Token support
  4. $httpProvider.defaults.xsrfCookieName = 'csrftoken';
  5. $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
  6. // Don’t strip trailing slashes
  7. $resourceProvider.defaults.stripTrailingSlashes = false;

4) Model can be represented as an angular’s resource

1
2
3
4
  1. angular.module('tweeterApp.services', ['ngResource'])
  2. .factory('Tweet', function($resource) {
  3. return $resource('/api/tweets/:id/');
  4. });

5) This gives a Tweet() object in JS, that has these default actions:

1
2
3
4
5
6
7
  1. {
  2. 'get': {method:'GET'},
  3. 'save': {method:'POST'},
  4. 'query': {method:'GET', isArray:true},
  5. 'remove': {method:'DELETE'},
  6. 'delete': {method:'DELETE'}
  7. };

6) To create a new object just do this:

1
2
3
  1. var newTeet = new Tweet();
  2. newTweet.name = "Look, a tweet!";
  3. newTweet.$save();

7) Get object by ID

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  1. // With a callback
  2. Tweet.get({id:123}, function(tweet){
  3. console.log(tweet);
  4. });
  5. // With a promise
  6. Tweet.get({id:123})
  7. .$promise.then(function(tweet) {
  8. $scope.tweet = tweet;
  9. });

8) Get a list of objects and add an object to it

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
  1. Tweet.query(function(response) {
  2. $scope.tweets = response;
  3. });
  4. $scope.submitTweet = function(text) {
  5. var tweet = new Tweet({text: text});
  6. tweet.$save(function(){
  7. $scope.tweets.unshift(tweet);
  8. })
  9. }

9) A hack to get current user id. Just put this into your Django template

1
2
3
4
5
6
7
8
  1. <script type="text/javascript">
  2. angular.module('tweeterApp.services')
  3. .factory('AuthUser', function() {
  4. return {
  5. id: "{{ user.id|default:''}}",
  6. }
  7. });
  8. </script>