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

1

How do I submit a post on Angular? I did a test here and required 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 do I send this post without this id?

When I send without the 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 request.

    
asked by anonymous 01.05.2014 / 22:45

1 answer

1

Although you have found the answer, I found it helpful 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 response from the server is always the same. Usually this means updating (total) a particular resource. In your case, you were using the PUT incorrectly, as you are creating a new feature. The most appropriate verb, as you have discovered, is POST.

Both Django and Angular follow spec, hence the error.

    
02.05.2014 / 08:30