1

Hi Guys I'm trying to Submit the data's using angularjs in Django by refering this post, But Its not working in my case,

views.py

def add(request, template_name="form.html"):
    if request.method == "POST":
        print request.POST.get('fname')
    return TemplateResponse(request, template_name)

form.html

<div ng-app="myApp">
<form action="." method="post" ng-controller="MyFormCtrl">{% csrf_token %}
     <input type="text" name="fname" id="fname" ng-model="userprofile.fname" placeholder="First Name">
     <input type="text" name="mname" id="mname" ng-model="userprofile.mname" placeholder="Middle Name">
     <input type="text" name="lname" id="lname" ng-model="userprofile.lname" placeholder="Last Name">
     <input type="text" name="email" id="email" ng-model="userprofile.email" placeholder="Email">
     <input type="text" name="phone" id="phone" ng-model="userprofile.phone" placeholder="Phone Number">
    <button ng-click="submit($event)">Save</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/angular/bower-angular-cookies/master/angular-cookies.js"></script>
<script type="text/javascript">
var nameSpace = angular.module("myApp", ['ngCookies']);
nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies',
function ($scope, $http, $cookies) {
    $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
    $scope.submit = function ($event) {
        $event.preventDefault();
        var in_data = jQuery.param({'fname': $scope.userprofile.fname,'csrfmiddlewaretoken': $cookies.csrftoken});
        $http.post("{% url 'add_angularjs' %}", in_data)
          .success(function(out_data) {
            $scope.card = angular.copy({});
        });
    }
 }]);
</script>

This is my code I Don't know what i Missed here, While I submitting the form its not triggering any thing.Please suggest me if I left any thing here and It will be greatfull for your suggestion. Thanks in advance.

1
  • If you already send the csrftoken in the request header, you don't really need to add it to the form and submitted data anymore. Commented Jan 28, 2016 at 12:54

2 Answers 2

1

Did you check what console logs tell you? Let me start from begining:

  1. You should not import angular-cookies script directly from raw github source because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled by default in most browsers. Download the script directly to you local disk or import it from proper CDN network.

  2. You use jQuery but you don't import it. Add below line to your code to import jquery (or stop using it at all).

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

  1. userprofile model is not defined in your controller's scope. You should add $scope.userprofile = {};

  2. $cookies.csrftoken is not defined. If you want to use csrftoken with $cookies you have to save it yourself, and then attach it to your post request. You can do it for example like this (simplest way in case of your code): $cookies.csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;

  3. So your fixed controller could like like this:

<script type="text/javascript">
    var nameSpace = angular.module("myApp", ['ngCookies']);
    nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies',
        function ($scope, $http, $cookies) {
            $scope.userprofile = {};
            $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            $cookies.csrftoken = document.getElementsByName("csrfmiddlewaretoken")[0].value;
            $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
            $scope.submit = function ($event) {
                console.log($cookies.csrftoken);
                $event.preventDefault();
                var in_data = {
                    fname: $scope.userprofile.fname,
                    csrfmiddlewaretoken: $cookies.csrftoken
                };
                $http.post("{% url 'add_angularjs' %}", in_data)
                  .success(function(out_data) {
                    $scope.card = angular.copy({});
                });
            }
     }]);
</script>

  1. Be sure to always check what's going on in web console debugger, and in your Django app. This will save you a lot of time ;)

I hope this post will help you with your issues.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your kind reply, I tired your fixed code and its returning the value as '{"fname":"Mark","mname":"Hendry","lname":"Luc","email":"[email protected]","phone":"8524552255522","csrfmiddlewaretoken" :"YuVNrDz1sfDwHal08wVCLDlCZsP8VkPg"}' dictionary , when i checked in console. and I used 'data = json.loads(request.body)' in the views to get the data, is this approach is right?
Yes, this is the way you have to use to get your data in a view.
Thank You so much, As you said i Used the approach, the data's are posted successfully, But I need to redirect the page to some url after the success, I tried with "$location.path = ('/')" but its not working, Showing error in console that '$location is not defined', Can you please suggest me how to redirect to another url after form submitted.Thank you so much.
0

Use verbatim block. So, your form.html looks like:

{% verbatim %}
<div ng-app="myApp">
    <form action="." method="post" ng-controller="MyFormCtrl">{% csrf_token %}
        ...
    </form>
</div>
{% endverbatim %}

Comments

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.