简体   繁体   English

如何将Django视图与angular js前端连接?

[英]How to connect a Django view with angular js Front end?

I'm fairly new to Django rest and angularjs. 我对Django rest和angularjs相当陌生。 I'm trying to create a Django view which will have a function and this function has to be called via a button in angular js. 我正在尝试创建一个具有功能的Django视图,该功能必须通过angular js中的按钮调用。 Can anyone please help me out? 有人可以帮我吗? Thanks 谢谢

This might help: Django - Angular Tutorial 这可能会有所帮助: Django-Angular教程

General answer would be: 1) Using for example Django REST expose your method (endpoint) 2) From Angular application send request to the previously exposed endpoint. 一般的答案是:1)使用例如Django REST公开您的方法(端点)2)从Angular应用程序向先前公开的端点发送请求。

say this is your Django/python api end point (assume controller file to be random.py) 说这是您的Django / python api端点(假设控制器文件为random.py)

def getRandomInfo(request):
try:
    result = database.getRandomInfo()
    return JsonResponse(result, content_type="application/json", safe=False)
except Exception as e:
    import traceback
    traceback.print_exc(e)
    return JsonResponse({error:'sorry'}, content_type="application/json", safe=False)

Via angular, provided you have resolved all the dependencies and have a functioning angular app and/or controller set up in your html/js 如果您已解决所有依赖性问题,并在html / js中设置了可正常运行的angular应用程序和/或控制器,则可以通过angular

you can call the api using below code 您可以使用以下代码调用api

app.controller("appControllerName", function ($scope, $http) {
    $http.get("{% url 'getRandomInfo' %}")
            .success(function (response, status) {
                response_data = response
                $scope.data = response_data;
            }).error(function (response, status) {
        $scope.status = status;
    });
  }

if you notice the {% url 'getRandomInfo' %} , this is defined in your urls.py , u'll have to add a line like this over there where getRandomInfo will have to be the 'name' of the url 如果您注意到{%url'getRandomInfo'%},它是在您的urls.py中定义的,则必须在该位置添加一行这样的内容,其中getRandomInfo必须是该URL的“名称”

url(r'^random/getRandomInfo/$',random.getRandomInfo, name='getRandomInfo'),

Over here you controller name is random and a function within that controller is def getRandomInfo, so django allows two ways to access this endpoint, either via the url r'^random/getRandomInfo/$ (yes regex is allowed here) or via the name as stated in the example here. 在这里,您的控制器名称是随机的,而该控制器中的函数是def getRandomInfo,因此django允许两种方式访问​​此端点,方法是通过url r'^ random / getRandomInfo / $(在此允许使用正则表达式)或通过名称如此处示例中所述。

Best of Luck :) 祝你好运:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM