GithubHelp home page GithubHelp logo

blacklocus / angular-django-rest-resource Goto Github PK

View Code? Open in Web Editor NEW
251.0 27.0 29.0 347 KB

An AngularJS module that provides a resource-generation service similar to ngResource, but optimized for the Django REST Framework.

License: Other

Python 100.00%

angular-django-rest-resource's Introduction

angular-django-rest-resource

An AngularJS module that provides a resource-generation service similar to ngResource, but optimized for the Django REST Framework. The biggest features:

  • Trailing slashes allowed in the resource URLs per the Django community norm.
  • The isArray methods like query allow for paginated responses. The pages will be streamed into the promise object.

Installation

Download angular-django-rest-resource.js and put it in your project. You may also do it the bower way:

bower install angular-django-rest-resource

Usage

Do this somewhere in your application HTML:

<script src="angular-django-rest-resource.js"></script>

Add this AngularJS module as a dependency to your AngularJS application:

angular.module('app', [..., 'djangoRESTResources']);

(where 'app' is whatever you've named your AngularJS application).

In your controllers and anything that needs to interact with the Django REST Framework services, inject the djResource service. Then you can create class-like objects that represent (and interact with) your Django REST Framework resources:

var Poll = djResource('/polls/:pollId/', {pollId:'@id'});

var myPoll = Poll.get({pollId:86}, function() {
    myPoll.readByUser = true;
    myPoll.$save();
});

For complete API, consider the documentation for $resource, as this module follows the API quite closely.

Launching The Testing and Demonstration App

This is a work in progress, but it gives some hints on usage in a real world scenario.

  1. Create a Python virtualenv.

  2. Install the dependencies:

     cd test
     pip install -r requirements.txt
    
  3. Set up the database and fixtures (if first time use).

     python manage.py syncdb
    
  4. Run the server:

     python manage.py runserver
    
  5. Point web browser to http://localhost:8000/.

angular-django-rest-resource's People

Contributors

georgewhewell avatar j0hnsmith avatar justintarthur avatar kosz85 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-django-rest-resource's Issues

Last page of paginated request

Is there is a way to determine when the last request of a series of paginated requests is completed? I need to make a function call that processes the complete result set of the request but cannot figure out a nice way for determining when the promise object contains all the paginated data.

lib as patches

This is more a discussion than an issue and I'm not sure if it would be practical or not but here goes...

This repo appears to be (I haven't looked too closely at the actual code) a fork of angular resource. It seems to me that it would be far easier to pull changes from angular resource if this project was a series of patches to angular resource (1 patch per django specific feature to add/change), then the patches could be applied against each new version of angular resource as it's released.

Obviously the patches would have to be modified from time to time when they don't apply cleanly however we'd avoid the current situation where angular resource has moved forward (a bit of an assumption) but this fork hasn't. I suspect it might even make adding new features even easier.

Please post some better examples on how to use this

Hi guys,

first of all: thanks a lot for this cool package.

I am just starting out with angular and I could really use some good examples on how to use this resource.

  1. How do I register it as a factory?
  2. How do I do a simple INSERT when listening to a form (for example add a new todo item to a todo-list).
  3. How do I do a eimple UPDATE (for example when editing an existing todo item to a todo-list).

Could somebody help me out?

For question 1) I think I have found the way to do it::

// services.js
var todoServices = angular.module('todoServices', ['djangoRESTResources'])
    .factory('Todo', function (djResource) { 
            return djResource('/api/todos/:todoId/', {todoId:'@id'});
        }
    );

Right now I am stuck with question 2). How do I insert a new item? This is my current code (NOT working):

<form ng-submit="TodoListCtrl.addTodo(todo)" novalidate>
              <div class="form-group">
                <label for="exampleInputEmail1">Description</label>
                <input ng-model="todo.description" id="todoDescription" type="text" class="form-control" placeholder="Todo">
              </div>
             <div class="checkbox">
                <label>
                  <input ng-model="todo.is_done" id="todoIsDone" type="checkbox"> ist done?
                </label>
              </div>
              <button ng-click="add(todo)" type="submit" class="btn btn-default">submit</button>
            </form>
// controllers.js
todoControllers.controller('TodoListCtrl', ['$scope', 'Todo',
    function ($scope, Todo) {
        $scope.todos = Todo.query();

        $scope.add = function(todo) {
            var newTodo = new Todo({description:todo.description, is_done:todo.is_done});
            newTodo.$save();
        }
    }
]);

Any ideas how to do this?

Fetch related objects

The HyperlinkedModelSerializer produces urls for related objects like that:

{
    url: "http://localhost:8000/orders/1/"
    cargo: "http://localhost:8000/cargo/1/"
}

Therefore a REST client needs no prior knowledge about url schema. But code for the navigation some annoying:

var Order = djResource('/orders/:order_id', {order_id: '@id'});
var orders = Order.query();
orders.$then(function(response) {
    angular.forEach(response.data, function(order) {
        var cargoUrl = order.cargo;

        // prevets port stripping from url
        // see https://github.com/angular/angular.js/issues/1243
        cargoUrl = cargoUrl.replace(/(:\d)/, '\\$1'); 

        order.cargo = djResource(cargoUrl).query();
    }
});
$scope.orders = orders;

Add a test.

This can be a tiny Django project with a requirements.txt to pull down the correct Django and Django REST Framework. A settings.py file that defaults to SQLite, an HTML file that streams some data from the Django service.

Result promise

Trying to use this in resolve block of route/state definition.
With ngResource I can access the result promise directly as .$promise. This explains why it's used.

While djResource also has a .$promise property it seems to be resolved after $http returns, but before it's populated with response data, so I can't use that like the ngResource one.
Something like this is required then (coffescript syntax):

resolve:
  apartment: (djResource, $stateParams, $q) ->
    deferred = $q.defer()
   djResource('/url/:id/').get {id: $stateParams.id}, (response) ->
      deferred.resolve(response)
   return deferred.promise

Am I missing something, is there a way to access the result promise?
Otherwise I think .$promise should be resolved after it's populated with data, mimicking ngResource.

save() 405 method not allowed

If I use the example in the readme I get 405 (METHOD NOT ALLOWED) when I call myPoll.save(). This is kind of expected as DRF doesn't (by default) allow POST requests to an instance, instead it wants a PUT request for model updates. Here's my solution

var Poll = djResource('/polls/:pollId/', {pollId:'@id'}, 
    {
        'update': 'PUT'
    }
);

var myPoll = Poll.get({pollId:86}, function() {
    myPoll.readByUser = true;
    //myPoll.$save();  // 405 METHOD NOT ALLOWED
    myPoll.$update();  // works
});

The update method can be automatically added here to always make it available, I'd send a pull request but it doesn't seem worth it for a one line change.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of blacklocus/angular-django-rest-resource!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library blacklocus/angular-django-rest-resource is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "blacklocus/angular-django-rest-resource",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Iterative Pagination

Why djResource fetch all pages if result is paginated?

How i can fetch pages on demand?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.