I'm fairly new to Django rest and 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. Can anyone please help me out? Thanks
This might help: Django - Angular Tutorial
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.
say this is your Django/python api end point (assume controller file to be 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
you can call the api using below code
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(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.
Best of Luck :)