问题
Edit: I'm using Django dev version so I do have access to JsonResponse (as seen below).
I'm messing around with Django and trying to make it work with AngularJS. Currently I'm attempting to query 4 rows from a database at a time and send the results as a JSON object to an Angular script. I just keep running into issues though - it won't work.
Here's where my code is at right now after a bunch of searching on StackOverflow to try and help myself out:
# views.py
class AJAXListMixin(object):
def dispatch(self, request, *args, **kwargs):
if not request.is_ajax():
raise Http404("Improper access.")
return super(object, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
return Project.objects.filter(added__lte=timezone.now())
def get(self, request, *args, **kwargs):
return JsonResponse(self.get_queryset(), safe=False)
class PageApi(AJAXListMixin, generic.ListView):
paginate_by = 4 # 4 results per page
ordering = '-added' # Most recent to oldest
----------------------
# models.py
class Project(models.Model):
title = models.CharField(max_length=100)
desc = models.TextField()
link = models.URLField(default=None, blank=True, null=True)
slug = models.SlugField(null=True)
added = models.DateField(_("Date Added"), default=datetime.today)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Project, self).save(*args, **kwargs)
def as_dict(self):
return {
"title": self.title,
"description": self.desc,
"link": self.link,
"slug": self.slug,
"date": self.added,
"previews": {
preview.as_dict() for preview in self.preview_set.all()
}
}
class Preview(models.Model):
project = models.ForeignKey(Project)
file = models.FileField(upload_to='project/preview/')
def __str__(self):
return "{project} Preview {id}".format(
project=self.project.title, id=self.id
)
def as_dict(self):
return {
"url": self.file.url
}
And here is the angular code I'm starting off with:
projects = angular.module("Projects", []);
projects.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
}]);
projects.controller("ProjectList", ['$scope', '$http', function ($scope, $http) {
$scope.projects = {};
$scope.page = 1;
$http.get('api/page/' + $scope.page)
.success(function (response) {
console.log(response)
})
.error(function (status) {
alert("Error. Check network logs.");
});
}]);
I want to store the response in the projects $scope variable so that I can do things with the data in my angular template.
回答1:
I'd recommend taking a look the following post:
http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html or this one https://thinkster.io/django-angularjs-tutorial/
It walks through setting up a REST API in Django to serialize your models, and specifying which fields are to serialized and returning JSON data using the Django Rest Framework.
Note that the example uses CoffeeScript and compiles it into JavaScript using GruntJS.
Instead your Angular controller should look more like the following (assuming you have a URL '/api/projects/', that routes to an API view that returns a JSON object containing multiple projects):
$scope.projects = [];
$http.get('/api/projects/').success(function(data) {
$scope.projects = data;
console.log($scope.projects);
});
Not sure how this would work with the additional pagination, but you can read more about it on the Django Rest Framework docs:
http://www.django-rest-framework.org/api-guide/pagination/
Hope this helps!
来源:https://stackoverflow.com/questions/27282360/django-and-angularjs-sending-query-json-data-to-angular