Passing URL parameter from TemplateView to BaseDatatableView
Issue #61
new
[added first as comment to issue 43, then removed]
I am trying to use the downloadable project as a template (the "TestModelList" and "TestModelListJson" views). In my case I want to use get_initial_queryset to filter on a "dataset" variable on the server b/c the model will have many 10s of 1000s of row.
But I can't figure out how to pass the URL parameter sent to the TemplateView on to the BaseDatatableView. If I leave the parameter out of the "datagrid_data" url, I render a grid, but no data and an alert for a Key Error for ['id'].
Thanks for the module! I'm almost there.
Here is my code:
urls.py
[ ...
path('datagrid/<str:label>', views.DatasetGrid.as_view(), name="ds_grid"),
path('datagrid_data/<str:label>', views.DatasetGridJson.as_view(), name="ds_grid_json"),
]
views.py
class DatasetGrid(TemplateView):
template_name = 'contribute/ds_grid.html'
class DatasetGridJson(BaseDatatableView):
order_columns = ['placeid', 'title', 'ccode']
def get_initial_queryset(self):
print('kwargs',self.kwargs)
return Place.objects.filter(dataset_id=self.kwargs['id'])
def filter_queryset(self, qs):
search = self.request.GET.get('search[value]', None)
if search:
qs = qs.filter(title__istartswith=search)
return qs
def prepare_results(self, qs):
json_data = []
for item in qs:
json_data.append([
item.placeid,
item.src_id,
item.title,
item.ccode,
])
return json_data
tablepage.html ...
<script type="text/javascript">
var DSGRID_JSON_URL = '{% url "ds_grid_json" ds.id %}';
...
</script>
...
ds_grid.js
$(document).ready(function() {
var dt_table = $('.datatable').dataTable({
...
ajax: DSGRID_JSON_URL
});
});
Comments (2)
-
-
Life saver @Klaas-Jan Gorter Thanks!
- Log in to comment
Django passes the keyword arguments in its url to the get/post method of the View instance. By storing the keyword arguments as variables in the class instance, they can be accessed later in the get_initial_queryset method.
The View class would look like this:
The corresponding url:
Finally, pass a dataset_id in the context for a django template and inside of the template put: