简体   繁体   中英

How to create CRUD using Django/Tastypie API?

I'm setting up a project using django-tastypie REST API and AngularJS. I'm fine with reading things from the json file through angular, but I cannot find a decent tutorial that would show me how to make even a simple CRUD application that isn't saving all the information in an object or whatever, but is manipulating the database through the tastypie api. Can any of you show me a tutorial of such sort or maybe just show me some sample code for this?

Thank you.

Use $resource - A factory which creates a resource object that lets you interact with RESTful server-side data sources.

Let's say you have Django model Book , and tastypie resource named BookResource . It's URL is /api/v1/book/. As you know, this URL actually is a resource, that means you can manipulate data in your Book model with GET, POST, DELETE, etc. requests. You can "map" the Angular $resource to this API resource in a way:

someModule.factory('bookResource', ['$resource', function($resource) {
    var apiResourceUrl = "/api/v1/book/:bookId/";
    // id - your model instance's id or pk, that is represented in API resource objects.
    var resource = $resource(apiResourceUrl, {bookId: '@id'}, {
        all: {
            method: 'GET', params: {}, // GET params that will included in request.
            isArray: true, // Returned object for this action is an array (miltiple instances).
        },
        get: {
            method: 'GET',
        },
        // [Define custom save method to use PUT instead of POST.][2]
        save: {
            /* But, the PUT request requires the all fields in object.
            Missing fields may cause errors, or be filled in by default values.
            It's like a Django form save.
            */
            method: 'PUT',
        },
        // [Tastypie use POST for create new instances][3]
        create: {
            method: 'POST',
        },
        delete: {
            method: 'DELETE',
        },
        // Some custom increment action. (/api/v1/books/1/?updateViews)
        updateViews: {
            method: 'GET',
            params: {"updateViews": true},
            isArray: false,
        },
    });
}]);

someModule.controller('bookCtrl', ['$scope', '$routeParams', 'bookResource',
  function ($scope, $routeParams, bookResource) {
    if ("bookId" in $routeParams) {
        // Here is single instance (API's detail request)
        var currentBook = bookResource.get({bookId: $routeParams.bookId}, function () {
            // When request finished and `currentBook` has data.

            // Update scope ($apply is important)
            $scope.$apply(function(){
                $scope.currentBook = currentBook;
            });

            // And you can change it in REST way.
            currentBook.title = "New title";
            currentBook.$save(); // Send PUT request to API that updates the instance
            currentBook.$updateViews();
        });
    }

    // Show all books collection on page.
    var allBooks = bookResource.all(function () {
        $scope.$apply(function(){
            $scope.allBooks = allBooks;
        });
    });

    // Create new
    var newBook = new bookResource({
        title: "AngularJS-Learning",
        price: 0,
    });
    newBook.$save();

}]);

Angular's docs provide more information how to make usage of resource really incredibly.

Here is the problem with urls. As I remember, Angular will send request to /api/v1/books/1 (without slash in the end) and you'll get 404 from tastypie. Let me check this.

[2] http://django-tastypie.readthedocs.org/en/latest/interacting.html#updating-an-existing-resource-put [3] http://django-tastypie.readthedocs.org/en/latest/interacting.html#creating-a-new-resource-post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM