Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django-Angular to make a AJAX call to a view

I'm trying to use Django-Angular to make a AJAX call to a view in Django. I'm following this guide here.

However, when I make a POST I'm getting the message: CSRF verification failed. Request aborted. It seems like the action as described in the docs process_something isn't being called as I shouldn't need the token.

Can anyone spot the issue, below is what I have tried so far...

Here is the relevant js controller script:

   var in_data = {action: 'process_something', somevar: $scope.somevar};
   var post_call = CbgenRestangularDjango.all('pin-verification/').post(in_data)

and the form:

<form ng-controller="PinValidationFormCtrl"  name="CompanyValidPinForm" class="bs-callout">
        <div class="col-xs-2">
            <input class="form-control" name="somevar" ng-model="somevar" type="text">
        </div>

        <div class="col-xs-2">
            <button type="button" class="btn btn-default" ng-click="submitPin()">Verify Pin</button>
        </div>
</form>

and the view:

class VerificationView(JSONResponseMixin, View):
    # other view methods

    @allowed_action
    def process_something(self, in_data):
        # process input data
        out_data = {
            'foo': 'bar',
            'success': True,
        }
        return out_data
like image 688
GrantU Avatar asked Dec 29 '13 17:12

GrantU


People also ask

Can you use AJAX with Django?

when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template. If you don't think Ajax is the best practice.

Can Django and Angular be used together?

Yes, creating API's using Django/DRF is sufficient to communicate with an Angular app. Below is an illustration of a basic architecture of a Django Angular application. API endpoints in Django will be served via the urls.py files using the DRF (Django Rest Framework.

How send data from AJAX to Django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

Is Django like Angular?

Django and Angular are both open-source web application frameworks utilized by developers around the globe. Both are based on the MVC concept.


3 Answers

The post() method accepts a config parameter to pass the X_CSRFTOKEN header:

var config = { headers : { 'X_CSRFTOKEN' : $cookies.csrf_token }};
var in_data = {action: 'process_something', somevar: $scope.somevar};
var post_call = 
CbgenRestangularDjango.all('pin-verification/').post(in_data, config);

In your view's template the form must include the token as follows:

<form ...>
    {% csrf_token %}
    ...
</form>

Note $cookies depends on ngCookies (see http://docs.angularjs.org/api/ngCookies.$cookies)

like image 67
miraculixx Avatar answered Sep 17 '22 19:09

miraculixx


You must pass the csrf token when sending a HTTP POST request.

Include {% csrf_token %} in your form or add a custom header X-CSRFToken. This should work.

like image 27
ghopst Avatar answered Sep 19 '22 19:09

ghopst


Its most likely you are missing a header in your angular's app module config.

Try setting the following

.config(function($httpProvider) {
  $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

Django applications do not require this header, but if it is missing, all invocations to: request.is_ajax() would return False, even for perfectly valid Ajax requests

Found here: http://django-angular.readthedocs.org/en/latest/integration.html Also there was an api change at angular version >= 1.1.x (this header default was dropped since that version). Perhaps Django did not catch up with their documentation in every part.


Maybe you just need to clear your browser cache as you might have an outdated cookie sending an invalid token letting the request mapping fail.

like image 41
angabriel Avatar answered Sep 18 '22 19:09

angabriel