0

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>
5
  • 2
    You have not given us sufficient information to help you. What is wrong with the code you have posted? What happens? What do you want to happen instead? What errors do you see? Commented Apr 19, 2016 at 8:59
  • @DanielRoseman the problem is this 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. Commented Apr 19, 2016 at 9:03
  • You're trying to use django template syntax in a js file but django doesn't render the javascript files Commented Apr 19, 2016 at 9:06
  • @Sayse then what exactly I can do to pass the value from django backend to angularjs frontend? Commented Apr 19, 2016 at 9:08
  • Look, you either populate a static page, server-side, in Django (using Views to render a Template) or you fetch the data dynamically (from the client, at the AngularJS level) using an API. The API can be either Django Rest Framework, or something you roll yourself, or a combination of the two. But the data has to come from somewhere! Commented May 13, 2016 at 11:43

1 Answer 1

2

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.

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

2 Comments

okay so I have to create api for this? Exactly what I want to do is fetch data from dynamodb (amazon web services db) using python framework and display it using angularjs
Yes, I guess creating an API might solve your problem. Even my project involves data stored in s3 bucket and we have defined our entire database schema using django models. I am querying our database in many more APIs that I have written in custom.py file, and then I send the response data generated from each one of the API in JSON (which are then handled in angular and the data is rendered at the front end).

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.