Django和AngularJS - 查询JSON数据发送到角 [英] Django and AngularJS - Sending query JSON data to Angular

查看:192
本文介绍了Django和AngularJS - 查询JSON数据发送到角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我使用Django的开发版本,所以我也有机会获得JsonResponse(如下图所示)

I'm using Django dev version so I do have access to JsonResponse (as seen below).

我瞎搞使用Django,并试图使其与AngularJS工作。目前,我试图在同一时间从数据库中查询4行,并将结果作为JSON对象发送到角脚本。我只是不停地运行到的问题,虽然 - 它不会工作。

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.

下面就是我的code是在现在一堆搜索在计算器上对自己尽量帮助出后:

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
        }

这是角code我开始了与:

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.

推荐答案

我建议考虑看看以下职位:

I'd recommend taking a look the following post:

http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html或者这一个 https://thinkster.io/django-angularjs-tutorial/

据走过在Django建立一个REST API序列化你的模型,并指定哪些字段使用的Django的REST框架序列化和返回JSON数据。

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.

请注意,此示例使用的CoffeeScript并将其编译为使用GruntJS的JavaScript。

Note that the example uses CoffeeScript and compiles it into JavaScript using GruntJS.

而不是你的角度控制器应看起来更像以下(假设你有一个网址'/ API /项目/,即路线,返回包含多个项目的JSON对象的API视图):

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

});

不知道如何做到这一点的额外分页工作,但你可以阅读更多关于它的Django的休息框架文档:

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 /分页/

希望这有助于!

这篇关于Django和AngularJS - 查询JSON数据发送到角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆