【问题标题】:Django, pass a javascript variable into ListView to filter a querysetDjango,将 javascript 变量传递到 ListView 以过滤查询集
【发布时间】:2021-02-07 23:01:44
【问题描述】:

我想在基于 Django 类的 ListView 中使用 Ajax 变量。

使用request.GET.get 将变量放入视图是没有问题的,但是,这样做似乎让我陷入了两难境地。

如果我使用def get(self, request),那么我在使用get_querysetget_context 时会遇到问题

如果我跳过使用 def get(self, request) 我在将 Ajax 变量放入视图时遇到问题。

我想寻求一些帮助以使其正常工作。最终目的是生成过滤后的context,用于生成电子邮件。

class ProductListSendView(LoginRequiredMixin, ListView):
    model = Product
    template = 'product/product_email.html'
    
    def get(self, request):
        _req_list =  json.loads(request.GET.get('ids', None))
        _res = [int(i) for i in _req_list]
        return _res
  
    def get_queryset(self, _res):
        queryset = super(ProductListSendView, self).get_queryset()
        qs = queryset.filter(id__in=_res)
        return qs

    def get_context_data(self):
        context = super(ProductListSendView, self).get_context_data()
        context['page_title'] = 'Authors'
        self.send_email(context)
        return context

js函数(为了完整性)

var getProducts = function () {
    var table = $('#product_list-table').DataTable();
    var ids = $.map(table.rows('.selected').data(), function (item) {
    return item[1]});


jQuery.ajax({
    type: 'GET',
    url: "/product/list/send/",
    data: { 
        ids: JSON.stringify(ids),
                },
    success: function(data) {},
    error: function(xhr, textStatus, error) {
        console.log(error);  
   } 
});
};

【问题讨论】:

    标签: python django ajax


    【解决方案1】:

    您可以覆盖get_queryset 并使用self.request 从那里访问请求:

        def get_queryset(self):
            _req_list =  json.loads(self.request.GET.get('ids', None))
            _ids = [int(i) for i in _req_list]
            queryset = super(ProductListSendView, self).get_queryset()
            qs = queryset.filter(id__in=_ids)
            return qs
    

    如果你不仅需要从get_queryset访问_ids,还需要从get_context_data访问,那么你可以将它存储在get方法中的self上,然后调用super进行常规操作处理:

        def get(self, request):
            _req_list =  json.loads(request.GET.get('ids', None))
            self._ids = [int(i) for i in _req_list]
            return super().get(request)
    

    当然,如果你这样做了,那么在get_querysetget_context_data 中你应该通过self._ids 访问它

    【讨论】:

    • 哎呀,这是错字,我更新了。 get_queryset 不带任何参数。
    猜你喜欢
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多