【发布时间】:2021-02-07 23:01:44
【问题描述】:
我想在基于 Django 类的 ListView 中使用 Ajax 变量。
使用request.GET.get 将变量放入视图是没有问题的,但是,这样做似乎让我陷入了两难境地。
如果我使用def get(self, request),那么我在使用get_queryset 和get_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);
}
});
};
【问题讨论】: