将数据从django视图发送到angularjs控制器

时间:2016-04-19 08:59:02

标签: python angularjs django

我正在尝试将数据从django views.py文件发送到angularjs controller.js文件但无法发送。 问题是我无法将视图文件中的数据发送到控制器。当我运行我的代码时,值{%steps%}不会更改为我在views文件中指定的值。 我不想使用Django休息框架来做这件事。 有没有其他方法来实现这一目标?如果是的话,请帮助我。

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 文件: -

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

1 个答案:

答案 0 :(得分:2)

这基本上就是我在我的一个主要的django项目中所做的(但我不是100%确定,无论是这还是这个,你要找的是什么,作为答案)。 所以,而不是views.py,我已经创建了一个custom.py文件,我在其中制作自定义API并在我的django应用程序的urls.py中调用它们(使用urlpatterns)。我还有另一组API,我正在使用django rest框架,我为它制作了视图而不是简单的视图。为了以防万一,您感兴趣,您可能会喜欢阅读this SO link

但是,既然你明确提到你不想使用django rest框架,我会给你一个custom.py文件的例子,如上所述。 您可以在下面找到custom.py,

中定义的API示例
@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")

然后,我的django应用程序中的urls.py看起来像:

urlpatterns = router.urls

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

我的控制器看起来像这样:

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

然后,您可以使用句柄渲染要在html文件中打印的变量。

希望,这有帮助。