0

I am trying to pass the data using angular $http post to django view but it is not happening. Every time I pass the data it shows empty dict, that means I am not using POST request correctly. I am new in integration django and angular app, so it would be great if someone can help me out with this.

app.js

vm.login = function() {
            vm.authMsg = '';
            var login_data = {'username': vm.account.username, 'password': vm.account.password};

            if(vm.loginForm.$valid) {

              $http
                .post('/login_app/', {login_data:JSON.stringify(login_data)})
                .then(function(response) {
                   console.log(login_data);

                  if ( !response.login_data ) {
                    vm.authMsg = 'Incorrect credentials.';
                    // vm.authMsg = response;
                  }else{
                    $state.go('app.dashboard');
                  }
                }, function() {
                  vm.authMsg = 'Server Request Error';
                });
            }
            else {
              vm.loginForm.account_username.$dirty = true;
              vm.loginForm.account_password.$dirty = true;
            }
          };

views.py

def login_app(request):
    if request.method == 'POST':
        print request.POST
        username = request.POST.get('username')
        password = request.POST.get('password')

        print 'username', username
        print 'password', password
        user = authenticate(username=username, password=password)
        print 'user', user
        if user:
            if user.is_authenticated():
                print 'user authenticate'
                login(request, user)
                return HttpResponse(json.dumps({}), content_type='application/json')
        else:
            return HttpResponse('<h1>Access Denied.<br>Wrong Credentials.</h1>')

login.html

<form role="form" ng-submit="login.login()" name="login.loginForm" novalidate="" class="form-validate mb-lg" method="post">

            <div class="form-group has-feedback">
               <input id="exampleInputUsername1" type="text" name="account_username" placeholder="Enter username" autocomplete="off" ng-model="login.account.username" required="" class="form-control" />
               <span class="fa fa-envelope form-control-feedback text-muted"></span>
               <span ng-show="login.loginForm.account_username.$dirty &amp;&amp; login.loginForm.account_username.$error.required" class="text-danger">This field is required</span>
            </div>
            <div class="form-group has-feedback">
               <input id="exampleInputPassword1" type="password" name="account_password" placeholder="Password" ng-model="login.account.password" required="" class="form-control" />
               <span class="fa fa-lock form-control-feedback text-muted"></span>
               <span ng-show="login.loginForm.account_password.$dirty &amp;&amp; login.loginForm.account_password.$error.required" class="text-danger">This field is required</span>
            </div>
            <div class="clearfix">
               <div class="checkbox c-checkbox pull-left mt0">
                  <label>
                     <input type="checkbox" value="" name="account_remember" ng-model="login.account.remember" />
                     <span class="fa fa-check"></span>Remember Me</label>
               </div>
               <div class="pull-right"><a ui-sref="page.recover" class="text-muted">Forgot your password?</a>
               </div>
            </div>
            <button type="submit" class="btn btn-block btn-primary mt-lg">Login</button>
         </form>

urls.py

from django.conf.urls import patterns, url
from login import views

urlpatterns = patterns('',
                    url(r'^$',views.home, name='home'),
                    url(r'^login_app/$',views.login_app, name='login_app'),
                    )
2
  • It looks to me like angular is sending {'login_data':{'username':...}} but the django app is trying to read username/password from the top level dict. (not from within login_data Commented Jun 20, 2016 at 7:01
  • @nephlm so I have to pass it in different variable? Commented Jun 20, 2016 at 7:04

1 Answer 1

2

Try this.

If you don't wrap/jsonify the login_data your existing view should be able to unpack it. I'm pretty sure angular automatically handles the json conversion, but I don't think django does.

vm.login = function() {
        vm.authMsg = '';
        var login_data = {'username': vm.account.username, 'password': vm.account.password};

        if(vm.loginForm.$valid) {

          $http
            .post('/login_app/', login_data)
            .then(function(response) {
               console.log(login_data);
            [...]

Looks like you also want to look to request.body to get your json data. If your in django < 1.4, it's something different.

def login_app(request):
    if request.method == 'POST':
        print request.body
        data = json.loads(request.body)
        print data
        username = data.get('username')
        password = data.get('password')
        [...]
Sign up to request clarification or add additional context in comments.

4 Comments

its not working. views.py printing this <QueryDict: {}> username None password None user None
@User0706 in your views.py you have get post data with postData = json.loads(request.body); as angular send http request with application/json content type. so see what you get in postData with json.loads.
@nephlm not working with request.body. Throwing this error username = request.body.get('username') AttributeError: 'str' object has no attribute 'get'
See the json.loads I added from ranakrunal9's comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.