我有一个模板,usersummary.html。它通过依赖URL参数显示有关特定用户的详细信息。我想在数据表中显示一些数据,这将涉及一个基于相同URL参数显示数据的AJAX数据表。
使用django-datatables-view:
views.py:
from django_datatables_view.base_datatable_view import BaseDatatableView
def usersummary(request, id):
return render(request, 'app/usersummary.html')
class testdatatableJSON(BaseDatatableView):
model = User
columns = ['item1', 'item2']
# This class uses django-datatables-view
# It returns JSON for the datatable to consume via AJAX
# I'd like to filter it to display only data relating to the user id defined in the url for template usersummary.html
urls.py
url(r'^(?P<id>\d+)/$', views.usersummary, name='usersummary'),
url(r'^testdatatable/$', testdatatableJSON.as_view(), name='testdatatable')
JS
$(document).ready(function() {
$('#table').DataTable({
"ajax": "{% url 'testdatatable' %}"
# This controls table in usersummary.html template
我认为在testdatatableJSON类中添加一个方法就像下面一样可行,但是没有(大概是因为id参数在通过AJAX消费时实际上没有传入)。如果我传入一个硬编码的例子来测试它,比如“id = 1”,它就可以了。
def get_initial_queryset(self, **kwargs):
return User.objects.filter(id=self.kwargs['id'])
有什么想法吗?
谢谢!
答案 0 :(得分:0)
views.py
def usersummary(request, id):
return render(request,{'user_id':id}, 'app/usersummary.html')
模板
var user_id= {{user_id}}
$('#table').DataTable({
"ajax": {"url":"{% url 'testdatatable' %}",
"data":{"id":user_id}}
# This controls table in usersummary.html template
然后将filter_queryset方法添加到testdatatableJSON类,如
def filter_queryset(self, qs):
# use request parameters to filter queryset
# simple example:
user_id = self.request.GET.get('id', None)
if user_id:
qs = qs.filter(id=user_id)
return qs
希望这会有效..