Django - 使用ajax post调用数据过滤对象不会返回任何内容

时间:2017-04-14 17:32:22

标签: python ajax django

我有以下Ajax POST调用:

$.ajax({
    type: "POST",
    url: "{% url 'meds:prescription' %}",
    data: {selected:'selected' , csrfmiddlewaretoken: "{{ csrf_token }}"},
    success: function(result) {
        window.location = "{% url 'meds:prescription' %}";
    }
});

选中的是一组id,例如[5, 9, 17]

以下观点:

class PrescriptionView(generic.ListView):
    template_name = 'meds/prescription.html'
    context_object_name = 'meds'
    model = Medicament

    def post(self, request, **kwargs):
        selected_ids = self.request.POST.getlist('selected[]')
        meds = self.get_queryset().filter(id__in=selected_ids)
        return render(request, self.template_name, {'meds': meds})

    def get_queryset(self):
        ids = self.request.POST.getlist('selected[]')
        return Medicament.objects.filter(id__in=ids)

    def get_context_data(self, **kwargs):
        ids = self.request.POST.getlist('selected[]')
        context = super(PrescriptionView, self).get_context_data(**kwargs)
        context.update({
            'meds': Medicament.objects.filter(id__in=ids),
            'date': datetime.now()
        })
        return context

我想要做的只是重定向到处方模板,使用来自post调用的数据过滤对象,但我的模板只是空的,我不确定我做错了什么..

1 个答案:

答案 0 :(得分:0)

您发送的字符串selected:'selected'不是数组。删除ajax处理程序中selected周围的单引号:

data: {selected:'selected' , csrfmiddlewaretoken: "{{ csrf_token }}"},

应该是:

data: {selected: selected, csrfmiddlewaretoken: "{{ csrf_token }}"},