我使用ajax post调用将数据数组发送到我的视图,如下所示:
class PrescriptionView(generic.ListView):
template_name = 'meds/prescription.html'
context_object_name = 'meds'
model = Medicament
def post(self, request, **kwargs):
selected_ids = request.POST.getlist('selected[]')
context = {'meds': Medicament.objects.filter(id__in=selected_ids)}
return super(PrescriptionView, self).render_to_response(context)
正如你可以看到我的视图是一个ListView,我想要的是列出那些带有来自selected_ids的id为Medicament.objects.filter(id__in=selected_ids)
的对象,但由于某种原因我不断收到以下错误:
AttributeError at /prescription/
'PrescriptionView' object has no attribute 'object_list'
Traceback:
File "/home/nids/cabin/dentist/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/nids/cabin/dentist/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/nids/cabin/dentist/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/home/nids/cabin/dentist/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/home/nids/cabin/meds/views.py" in post
38. return super(PrescriptionView, self).render_to_response(context)
File "/home/nids/cabin/dentist/lib/python3.5/site-packages/django/views/generic/base.py" in render_to_response
132. template=self.get_template_names(),
File "/home/nids/cabin/dentist/lib/python3.5/site-packages/django/views/generic/list.py" in get_template_names
200. if hasattr(self.object_list, 'model'):
Exception Type: AttributeError at /prescription/
Exception Value: 'PrescriptionView' object has no attribute 'object_list'
修改
Ajax电话:
jQuery(document).ready(function($) {
$( "#continue" ).click(function() {
var selected = $("#meds").bootgrid("getSelectedRows");
console.log(selected);
$.ajax({
type: "POST",
url: "{% url 'meds:prescription' %}",
data: {selected:'selected' , csrfmiddlewaretoken: "{{ csrf_token }}"},
success: function(result) {
$('#message').html("<h2>Contact Form Submitted!</h2>")
}
});
});
});
注意:selected是一个数组
答案 0 :(得分:1)
有一次,我在发送数据数据时使用了以下模式:
var roles = data_selected();
$.ajax({
type: 'POST',
url: '/get_roles/',
data: {'roles[]': roles},
});
});
而且,在django视图中,我
def get_roles(request):
roles = request.POST.getlist('roles[]')
....
你能和你分享ajax电话吗?我认为发送时数据可能会混乱?
处理邮寄申请:
def post(self, request, **kwargs):
selected_ids = request.POST.getlist('selected[]')
meds = self.get_queryset().filter(id__in=selected_ids)
return render(request, self.template_name, {'meds': meds })