Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.)

share|improve this question
    
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. –  stormlifter Jul 15 '14 at 19:24
    
thanks -- I've started reading but obviously not far along enough to understand the post/get things. –  wgw Jul 15 '14 at 20:39

1 Answer 1

up vote 2 down vote accepted

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']
  [...]
share|improve this answer
    
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!) –  wgw Jul 18 '14 at 22:57
    
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!) –  wgw Jul 18 '14 at 23:15
    
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. –  wgw Jul 18 '14 at 23:37
    
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/… –  Luke Skywalker Jul 19 '14 at 6:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.