【问题标题】:Django with AngularJS带有 AngularJS 的 Django
【发布时间】:2018-05-03 20:22:01
【问题描述】:

如果我所做的正确与否,我想得到一个建议。 我有一个网站,您可以在主页中搜索数据库中的项目,当找到您的项目时,您按名称,您将被带到其详细信息页面。 我知道 Django 能够在 url 中发送选定的项目 ID,然后我可以呈现详细信息页面并在上下文中发送对象。但是我想在详细信息页面中以 angularJS 中的 JSON 形式接收对象,因此我正在读取 angular 控制器中的 url,然后提取 id 并将其作为 http 请求发送到视图以获取项目。

我将在这里放一个示例代码:

型号:

class Item(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False)
    feature_1 = models.IntegerField(null=False, blank=False)
    feature_2 = models.IntegerField(null=False, blank=False)
    feature_3 = models.IntegerField(null=False, blank=False)

    def to_json(self):
        json_data = {
            'id': self.id,
            'name': self.name,
            'feature_1': self.feature_1,
            'feature_2': self.feature_2,
            'feature_3': self.feature_3,
        }
        return json_data

观看次数:

def home_page(request):
    return render_to_response('home.html', {},
                                  context_instance=RequestContext(request))

def item_details_page(request):
            return render_to_response('item_details.html', {},
                                          context_instance=RequestContext(request))

def get_item_details(request):
    item_id = int(json.loads(request.body)['item_id'])
    selected_item = Item.objects.get(pk=item_id).to_json()

    return JsonResponse({'item': selected_line}, content_type="application/json", safe=False)

角度控制器

ngApp.controller('ItemDetailsCtrl', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {

    $scope.item = null;

    $http({
        method: 'POST',
        url: url_get_item,
        data: {
            item_id: parseInt(window.location.href.toString().split('item_details/')[1])
        }
    }).then(function successCallback(response) {
        $scope.item = response.data.item;
    }, function errorCallback(response) {

    });


}]);

这是个好方法吗? 使用 Django 能力不是一个坏主意吗? 有没有更好的方法来处理 django 在 angularJS 中返回的项目?

谢谢。

【问题讨论】:

    标签: angularjs django


    【解决方案1】:

    我认为Django + Angular 的最佳方式是使用Django Rest Framework。它可以更轻松地返回 JSON 对象,专为这种情况而设计。但是你的方式也是可以接受的,特别是如果有任何其他页面,Angular 不提供服务。

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2014-05-25
      • 2013-10-19
      • 2015-10-24
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      相关资源
      最近更新 更多