Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django class based views, POST method not allowed

I am in the process of learning django.

I am getting method post not allowed 405 error. I have POST defined in my view class as below.

class LoginView(views.APIView):

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = HUserAuthSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

urls.py in users app has following:

url(r'^login/$', LoginView.as_view(), name='login'),

urls.py at project level has following:

url(r'^users/', include(users_urls)),

that makes my URL

http://localhost:8000/users/login/

I can see the URL from in the log as above.

frontend angularJS code is as follows:

appData.service("signInService", function($http, $q) { 

this.signIn = function (signin) {

    var url = "http://localhost:8000/users/login/";
    console.log(url);

    var defer = $q.defer();

    $http.post(url, { 
          email: signin.email,
          password: signin.password}, 
               {callback:"JSON_CALLBACK", _dont_enforce_csrf_checks:"True"}, {post:{method: "JSONP"}})
        .success(function(response){
            defer.resolve(response);
        })
        .error(function(response){
            defer.reject(response);    
        })

      return defer.promise;
    };  

});

like image 406
byedma Avatar asked Nov 08 '22 20:11

byedma


1 Answers

Are you possibly posting to http://localhost:8000/api/v1/users/login instead of http://localhost:8000/api/v1/users/login/ (notice the trailing slash)

Try modifying

url(r'^login/$', LoginView.as_view(), name='login'),

to

url(r'^login/?$', LoginView.as_view(), name='login'),
like image 96
Zack Tanner Avatar answered Nov 14 '22 21:11

Zack Tanner