user6361549 user6361549 - 6 months ago 284
jQuery Question

Url arguments with Django ajax datatable?

I have a template, usersummary.html. It shows details about a specific user by relying on a URL parameter. I'd like to display some of the data in a datatable, which would involve an AJAX datatable displaying data based on the same URL parameter.

Using 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


I'd thought that adding a method to the testdatatableJSON class like below would work, but alas not (presumably because the id parameter isn't actually passed in when consumed via AJAX). If I pass in a hard-coded example to test it, like "id=1", it works fine.

def get_initial_queryset(self, **kwargs):
return User.objects.filter(id=self.kwargs['id'])


Any ideas?

Thanks!

Answer

views.py

def usersummary(request, id):
    return render(request,{'user_id':id}, 'app/usersummary.html')  

template

var user_id= {{user_id}}
$('#table').DataTable({
"ajax": {"url":"{% url 'testdatatable' %}",
"data":{"id":user_id}}
# This controls table in usersummary.html template 

Then add filter_queryset method to the testdatatableJSON class like

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

hope this will work..