user6361549 user6361549 - 10 months ago 387
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:

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

url(r'^(?P<id>\d+)/$', views.usersummary, name='usersummary'),
url(r'^testdatatable/$', testdatatableJSON.as_view(), name='testdatatable')


$(document).ready(function() {
"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?



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


var user_id= {{user_id}}
"ajax": {"url":"{% url 'testdatatable' %}",
# 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..