djangocon 2014 angular + django

40
Angular + Django A match made in heaven

Upload: nnja

Post on 30-Nov-2014

751 views

Category:

Software


3 download

DESCRIPTION

Djangocon 2014 angular + django

TRANSCRIPT

Page 1: Djangocon 2014 angular + django

Angular + DjangoA match made in heaven

Page 2: Djangocon 2014 angular + django

github.com/nnja/tweeter

Page 3: Djangocon 2014 angular + django

Django Templates… are not my favorite

Page 4: Djangocon 2014 angular + django

● Need to refresh the page to submit a form● Tough to write JS around template tags● Difficult to Unit Test● Template tags can be hard to grok for front

end devs

… also end tags are annoying

Page 5: Djangocon 2014 angular + django

Forms get complex, fast.

Page 6: Djangocon 2014 angular + django

Why Endpoints are Better (IMHO)

● Faster - no waiting for a page to reload● Swap frameworks - Ability to use any javascript

framework, and switch them out easily.● Reusable - Have a mobile app? Your backend is

already done!

Page 7: Djangocon 2014 angular + django

Dogfooding

If your endpoints are public, you can eat your own dogfood by consuming them internally.

Page 8: Djangocon 2014 angular + django

REST Frameworks are Standard

Front End Devs know how to use them.

Page 9: Djangocon 2014 angular + django
Page 10: Djangocon 2014 angular + django

AngularJS

● MVC - Responsibilities are separated● Single page app. That means no refreshes for new

content, and a better user experience● Scope - Variables are bound between JS & View -

no nasty JQuery● Easily Unit Tested

Page 11: Djangocon 2014 angular + django

The bad

You have to use Javascript

Page 12: Djangocon 2014 angular + django

If you don’t like it...

Page 13: Djangocon 2014 angular + django

Use another framework

Excellent presentation on choosing a JS Framework

http://brianholt.me/

Page 14: Djangocon 2014 angular + django

Let’s build a Tweeter http://github.com/nnja/tweeter

Page 15: Djangocon 2014 angular + django

Requirements

1. Display a list of tweets from all Users2. Display my tweets (logged in User)3. Show my profile - username, etc.

Page 16: Djangocon 2014 angular + django

Our endpoints are created w/ DRF

Django Rest Framework- Easily create a REST endpoint for your application.

Page 17: Djangocon 2014 angular + django

Our Modelclass Tweet(models.Model):

user = models.ForeignKey(User)

text = models.CharField(max_length=140)

timestamp = models.DateTimeField(auto_now_add=True)

class Meta:

ordering = ['-timestamp']

Page 18: Djangocon 2014 angular + django

Our endpoints

/api/users/

/api/tweets/

/api/users/:id

/api/tweets/:id

Page 19: Djangocon 2014 angular + django

GET /api/tweets/

HTTP 200 OK

Vary: Accept

Content-Type: text/html; charset=utf-8

Allow: GET, POST, HEAD, OPTIONS

[

{

"text": "Bob is the coolest name EVAR",

"user": "bob",

"timestamp": "2014-08-29T18:51:19Z"

}

]

Page 20: Djangocon 2014 angular + django

Configuring Angular

Page 21: Djangocon 2014 angular + django

Step 1.

Include angular.js

Throw ng-app into one of your tags. Everything within those tags is now an angular app.

<html lang="en" ng-app="tweeterApp">

Page 22: Djangocon 2014 angular + django

Angular tags and Django template tags conflict.

{{ }}

UH OH

Page 23: Djangocon 2014 angular + django

Tell angular to use different tagsI like [[ this ]]

or use {% verbatim %} {% endverbatim %}

Page 24: Djangocon 2014 angular + django

static/js/app.js

$interpolateProvider.startSymbol('[[').endSymbol(']]');

$httpProvider.defaults.xsrfCookieName = 'csrftoken';

$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

$resourceProvider.defaults.stripTrailingSlashes = false;

Page 25: Djangocon 2014 angular + django

Angular Resources

A wrapper around a REST Endpoint at a location.

angular.module('tweeterApp.services', ['ngResource'])

.factory('Tweet', function($resource) {

return $resource('/api/tweets/:id/');

});

Page 26: Djangocon 2014 angular + django

Default Actions{ 'get': {method:'GET'},

'save': {method:'POST'},

'query': {method:'GET', isArray:true},

'remove': {method:'DELETE'},

'delete': {method:'DELETE'} };

Page 27: Djangocon 2014 angular + django

Creating a new objectvar newTeet = new Tweet();

newTweet.name = "Look, a tweet!";

newTweet.$save();

Page 28: Djangocon 2014 angular + django

CallbacksTweet.get({id:123}, function(tweet){

console.log(tweet);

});

Page 29: Djangocon 2014 angular + django

VS PromisesTweet.get({id:123})

.$promise.then(function(tweet) {

$scope.tweet = tweet;

});

Page 30: Djangocon 2014 angular + django

Scope

You change a value in the controller, and it’s automagically updated in the view.

And vice versa.

Page 31: Djangocon 2014 angular + django

Angular ControllerstweeterControllers.controller('TweetCtrl', function

TweetCtrl($scope, Tweet) {

...

});

Page 32: Djangocon 2014 angular + django

The meatTweet.query(function(response) {

$scope.tweets = response;

});

$scope.submitTweet = function(text) {

var tweet = new Tweet({text: text});

tweet.$save(function(){

$scope.tweets.unshift(tweet);

})

}

Page 33: Djangocon 2014 angular + django

Can’t get rid of all the templates

Used to pass information from django-land to angular.

Gives us our static URL so we can load assets (css/js)

Page 34: Djangocon 2014 angular + django

Interacting with Django Templates<script type="text/javascript">

angular

.module('tweeterApp.services')

.factory('AuthUser', function() {

return {

id: "{{ user.id|default:''}}",

}

});

</script>

Page 35: Djangocon 2014 angular + django

Angular UI Routing .config(function ($stateProvider, $urlRouterProvider) {

...

$urlRouterProvider.otherwise('/');

$stateProvider

.state('tweets', {

url: '/',

templateUrl: 'static/tweeter/partials/tweet-list.html',

controller: 'TweetCtrl',

})

};

Page 36: Djangocon 2014 angular + django

Routing in Angular

Drop this in your base template

<div ui-view></div>

Depending on the route, the correct partial will be rendered and inserted.

Page 37: Djangocon 2014 angular + django

Partials

Just vanilla HTML and Angular.

Keep them in an accessible static folder.

Page 38: Djangocon 2014 angular + django
Page 39: Djangocon 2014 angular + django

Demo time!

Page 40: Djangocon 2014 angular + django

Bye Everybody!

@nnjagithub.com/nnja/tweeter