Question

I'm using Django REST framework. Writing API works if you manually enter data on a page: http://example.com/en/api/v1/add_comment/

views.py (API)

class AddComment(generics.CreateAPIView):
"""
Create new comment.
Example API structure:
{
    "post_pk": 1,
    "name": "MyName",
    "email": "example@email.com",
    "text": "This is text message!"
}
"""
model = Comment
serializer_class = CommentSerializers

And api works.

controllers.js

var app = angular.module('controllers', []);

app.controller('CommentAddCtrl', function($scope, Restangular){
    $scope.logComment = function(mail, name, text){
        var url = window.location;
        var pk = url.hash.split('$pk:')[1];
        var url_add_comment_api = './en/api/v1/add_comment';

        if (mail === undefined || name == undefined || text === undefined)
            alert ('Error!');
        else {
            var comment = {
                  post_pk: pk,
                  name: name,
                  email: mail,
                text: text
                };
            this.add_comment = Restangular.all(url_add_comment_api).post(comment);
            }           
    };
});

When the console getting error: POST http://example.com/en/api/v1/add_comment/ 403 (FORBIDDEN)

Was it helpful?

Solution

You may be missing a CSRF token somewhere in there. See more here: Django Cross Site Request Forgery Protection

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top