How to submit a post using Django Rest Framework and Angular.js

Asked

Viewed 467 times

1

How do I submit a post on Angular? I ran a test here and requires you to report to PK:

index.controller('EditController', function($scope, $http) {
$scope.save = function() {
    var in_data = { name: $scope.Job.name, description: $scope.Job.description };
    $http.put('job/5/', in_data)
        .success(function(out_data) {
            console.log("Success!");
        }).
         error(function(data, status, headers, config) {
            console.log(status, data);
        });
};
});

The problem would be specifically here:

$http.put('job/5/', in_data)

Obviously the id could not go in the url. How to send this post without this id?

When sending without id this is the error:

405 METHOD NOT ALLOWED
{"detail": "Method 'PUT' not allowed."}

My urls.py:

url(r'^job/(?P<pk>[0-9]+)/$', views.job_detail, name="add_job"),

My views.py:

try:
    job = Job.objects.get(pk=pk)
except Job.DoesNotExist:
    return Response(status=status.HTTP_404_NOT_FOUND)

elif request.method == 'PUT':
    serializer = JobSerializer(job, data=request.DATA)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Edited:

I was able to change the "PUT" method to "POST" in views.py and using $http.post() when making the requisition.

  • If you have found the solution, create an answer, do not put within the question as you did. Welcome.

  • 1

    Sorry for the mistake, I’ll follow the recommendation next time. Hug!

1 answer

1

Although I have found the answer, I thought it best to clarify something that might be useful:

According to the RFC 2616 verb PUT is an idempotent method, that is, no matter how many times I repeat the request, the server response is always the same. Generally this means the (total) upgrade of a given resource. In your case, you were using PUT wrong, since you are creating a new resource. The most appropriate verb, as you discovered, is POST.

Both Django and Angular follow the spec, hence the error.

  • Thanks for the clarification! Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.