I am a beginner in django framework and DataTables. Currently, I am trying to load a jquery DataTable with the data coming back from the server. I have built an api using django REST framework to pass the data to DataTables. However, I am not able to load the DataTable from the json data from the server. Please find below my code snippets and pleas tell me if I am missing anything.
the index.html looks like following.
<table id="packages_table" class="table table-striped table-bordered">
<thead>
<tr>
<th>User Name</th>
<th>First Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#packages_table').dataTable({
ajax: 'http://127.0.0.1:3434/user/',
columns: [
{ "data": "username"},
{ "data": "first_name"},
{ "data": "email"},
]
});
});
</script>
urls.py, where I have defined the viewset, serializer and router looks like this.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'user', UserViewSet)
# Wire up our API using automatic URL routing.
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include(datagrid_urls)),
#configure to use the browsable API by adding REST framework's login and logout views
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And, below is the json data from the url.
[
{
"url": "http://127.0.0.1:3434/user/2/",
"username": "morgoth",
"first_name": "morgoth",
"email": "duke.valafar@gmail.com",
"is_staff": true
},
{
"url": "http://127.0.0.1:3434/user/3/",
"username": "anna",
"first_name": "",
"email": "anna@anna.com",
"is_staff": false
},
{
"url": "http://127.0.0.1:3434/user/4/",
"username": "adam",
"first_name": "",
"email": "ada@abc.com",
"is_staff": false
}
]
And here is my debug bookmarklet