3

Why can't I use params or data with $http to communicate with Django?

I have an angularjs page that gets data from a django view. In one case, I have a django view called /display that grabs a file off the server and displays it as plain text.

this.loadfile = function (clickedItem) {
    $http({method: 'GET' , url: '/display/'+ clickedItem.fileName})
        .success(function(data) {
                $scope.fileView.text = data;

        });
};

The call to /display/myfile.txt works nicely, since the filename is a simple string, as is the returned data.

Now I need to send a more complex, multiline parameter to django: a list of searchStrings and a list of filenames:

  this.concord = function (searchStrings, filenames) {

        $http({method: 'GET' ,
                url: '/concord/',
                data: {"searchStrings":searchStrings, "filenames":filenames}
            )
            .success(function(data) {
                console.log(data); // log the data coming back.
                $scope.concord = data;
            });
    };

According to AngularJS - Any way for $http.post to send request parameters instead of JSON?, that should work with

url(r'^concord/(?P<jsondata>.*)$', views.concord, name="concord"),

where my view is:

def concord(request,jsondata) :
    jObj=simplejson.loads(jsondata)
    return HttpResponse(jObj["files"])

(I tried parsing request.body as well; was empty)

On the other hand, if I explicitly attach it to the url, I do get something back:

 $http({method: 'GET',
                url: '/concord/'+JSON.stringify({"searchStrings":searchStrings, "filenames":filenames}),

            }
            )
            .success(function(data) {
                console.log(data);
                $scope.concordResults = data;
            });

That works!

But I must be doing this in worst way possible. Is there a way to use params or data to communicate with Django?

(PS: I have avoided django-angular package because I am already overwhelmed with learning packages: django rest, angular, bootstrap, etc... I really just want to start with bare-bones communication between angular and django. Later I will dive into more packages.)

2
  • django-rest-framework.org < Look into that, it helps Django act more "RESTful" and makes it a lot easier for you to make data-driven views for angular to consume. Commented Jul 15, 2014 at 19:24
  • thanks -- I've started reading but obviously not far along enough to understand the post/get things. Commented Jul 15, 2014 at 20:39

1 Answer 1

3

If you look at angularjs docs (https://docs.angularjs.org/api/ng/service/$http) you see that you can get params and post data like json in your case.

When you post, you'll do something like this:

$http.post('http://www.example.com/post_data_url',
           { 'key': $scope.value }
          );

On django side, don't add any parameter to the URL, the JSON will be inside the request, in the body to be more precise:

import json

def concord(request):
  dictionary = json.loads(request.body)
  # to use the value, access the created dictionary
  print dictionary['key']
  [...]
Sign up to request clarification or add additional context in comments.

4 Comments

The main difference here is you are using POST rather than GET; I will test it further. For the moment, I'm getting 403 (FORBIDDEN) for POST (even though I'm on local host, this is probably a crsf issue). I'm running it with the JSON.stringify approach for the moment. Will see if your method works once I figure out the "Forbidden" problem. (Thanks!)
Yes, that did it! I put in a @csrf_exempt for the moment, and got around that error. Thanks! It was simply that the GET does not have a body...(I'm guessing). Now it is a question of understanding csrf between angular and django...(more work!)
OK, just for the record: to avoid "forbidden", in my Django views: from django.views.decorators.csrf import ensure_csrf_cookie, then @ensure_csrf_cookie for each (?) view that communicates with angular.
There is already a question on csrf management with angularjs/django. The answer is clear and is working. It is also more elegant than the use of @ensure_csrf_cookie: stackoverflow.com/questions/18156452/…

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.