User0706
User0706

Reputation: 1085

Send data from django views to angularjs controller

I am trying to send data from django views.py file to angularjs controller.js file but unable to send it. The problem is this that I am unable to send data from views file to controller. And when I run my code then the value {%steps%} doesn't change to the value I have assigned in views file. I don't want to use Django rest framework for doing this. Is there any other way of achieving this? If yes, then please help me out.

views.py:

from django.shortcuts import render
from django.conf import settings
from user_data.models import GetData
import json

def home(req):
    return render(req, 'index.html')

def userData(req):
    if req.method == 'GET':
        user_data = GetData().getAllData()
        context_dict = {'user_data1' : json.dumps(user_data[0]),
                        'user_data2' : json.dumps(user_data[1]),
                        'user_steps' : json.dumps(2000)}

        return render(req, 'index.html', context_dict)

controller.js :

'use strict';

MetronicApp.controller('DashboardController', function($rootScope, $scope, $http, $timeout) {
    $scope.$on('$viewContentLoaded', function() {   
        // initialize core components
        Metronic.initAjax();
    });
    $scope.steps = {{user_steps|safe}};
});

html file:-

<div ng-controller="DashboardController" class="margin-top-10">
    <div class="row ">
                <div class="col-md-12 col-sm-12">
                    <div class="portlet light ">
                            <div class="portlet-title">
                                <div class="caption">
                                    <i class="icon-cursor font-purple-intense hide"></i>
                                    <span class="caption-subject font-purple-intense bold uppercase">Tracker Report</span>
                                </div>
                                <div class="actions">
                                    <a href="javascript:;" class="btn btn-sm btn-circle btn-default easy-pie-chart-reload">
                                    <i class="fa fa-repeat"></i> Reload </a>
                                </div>
                            </div>
                            <div class="portlet-body">
                                <div class="row">
                                <div class="col-md-3">
                                    <div class="easy-pie-chart">
                                        <div class="number transactions" data-percent="55">
                                            <span>{$ steps $}</span>
                                        </div>
                                        <!-- <a class="title" href="#"> -->
                                        Steps <!-- <i class="icon-arrow-right"></i> -->
                                        </a>
                                    </div>
                                </div>
                                <div class="margin-bottom-10 visible-sm">
                                </div>
                                <div class="col-md-3">
                                    <div class="easy-pie-chart">
                                        <div class="number visits" data-percent="85">
                                            <span>
                                            +85 </span>
                                            %
                                        </div>
                                        <!-- <a class="title" href="#"> -->
                                        Sleep<!-- <i class="icon-arrow-right"></i> -->
                                        </a>
                                    </div>
                                </div>
                                <div class="margin-bottom-10 visible-sm">
                                </div>
                                <div class="col-md-3">
                                    <div class="easy-pie-chart">
                                        <div class="number bounce" data-percent="46">
                                            <span>
                                            +46 </span>
                                            %
                                        </div>
                                        <!-- <a class="title" href="#"> -->
                                        Calories <!-- <i class="icon-arrow-right"></i> -->
                                        </a>
                                    </div>
                                </div>
                                <div class="margin-bottom-10 visible-sm">
                                </div>
                                <div class="col-md-3">
                                    <div class="easy-pie-chart">
                                        <div class="number bounce" data-percent="32">
                                            <span>
                                            +32 </span>
                                            %
                                        </div>
                                        </a>
                                    </div>
                                </div>

                            </div>
                            </div>
                        </div>
                </div>
</div>

Upvotes: 0

Views: 3003

Answers (1)

Shubhanshu
Shubhanshu

Reputation: 1015

This is basically what I have done in one of my major django projects (but I am not 100% sure, whether this is or this ain't what you are looking for, as an answer). So, instead of views.py, I have made a custom.py file in which I make custom APIs and call them (using urlpatterns) in the urls.py of my django app. And I have another set of APIs for which I am using django rest framework, for which I make viewsets rather than simple views. Just in case, you are interested, you might like reading this SO link.

But since, you specifically mentioned that you don't want to use django rest frameworks, I will give you an example of the custom.py file, as mentioned above. Below you will find a sample of an API defined in a custom.py,

@api_view(['GET'])
def get_user_details(request):
    """
    API View that gives a user detail

    ---

    parameters:
        - name: email
          description: The email of the user based on which his/her information has been extracted
          required: true
          type: string

    responseMessages:
        - code: 400
          message: Email required as GET parameters.
          message: User not found.
        - code: 200
          mesage: User details sent successfully

    consumes:
        - application/json
        - application/xml
    produces:
        - application/json
        - application/xml

    """

    email = request.query_params.get('email', None)

    if email is None:
        return HttpResponseBadRequest("Email required as GET parameters.")

    try:
        user = User.objects.get(username=email)
    except User.DoesNotExist:
        return HttpResponseBadRequest("User not found.")
  
    response_data = {'id': user.id, 'first_name': user.first_name, 'last_name': user.last_name,}

    return HttpResponse(json.dumps(response_data), content_type="application/json")

And subsequently, the urls.py in my django app looks like:

urlpatterns = router.urls

urlpatterns = urlpatterns + [
    url(r'get_user_details/', get_user_details),
]

My controller would look something like this:

  CheckEmail : function (current) {
    return $http({
        method: 'GET',
        url: baseAPI + 'admin/get_user_details/',
        params: {email: current},
    })
  },

And then subsequently, you may be able to render the variable you wish to print in your html file using handles.

Hope, it helps.

Upvotes: 2

Related Questions