I have a Datatable that's working perfectly, and I wanted Server-side process to be true and not client-side.
But when I enable server-side the sorting, paging and search became faulty.
TestCase: https://codepen.io/TheNerdy97/pen/gOvNeeo?html-preprocessor=pug
I'm using this module https://github.com/izimobil/django-rest-framework-datatables
For seamless integration between Django REST framework and Datatables.
I did as the doc said but it still won't work as expected.
models.py
from unittest.util import _MAX_LENGTH
from django.db import models
#from django.utils.translation import gettext as __
# Create your models here.
class Fresh(models.Model):
code = models.CharField(("code"), max_length=255)
orbs = models.IntegerField(("orbs"))
orbs_display = models.CharField(('orbs_display'), max_length=255)
price = models.IntegerField(("price"))
price_display = models.CharField(('price_display'), max_length=255)
images = models.CharField(("images"), max_length=10000000)
date = models.CharField(("date"), max_length=255)
class Meta:
ordering = ['code', 'orbs', 'price']
def __str__(self):
return self.code
views.py
from django.shortcuts import render
from accounts.models import Fresh, Orbs
from rest_framework import viewsets
from accounts.serializers import FreshSerializer
from django.core import serializers
# Create your views here.
def index (request):
return render(request, 'index.html')
class FreshViewSet(viewsets.ModelViewSet):
queryset = Fresh.objects.all().order_by('price')
serializer_class = FreshSerializer
urls.py
import accounts
from . import views
from django.urls import path, include, re_path
from rest_framework import routers
from main import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'fresh', views.FreshViewSet)
router.register(r'orbs', views.OrbsViewSet)
urlpatterns = [
path('', views.index, name='index'),
path('fresh', views.fresh, name='fresh'),
re_path('^api/', include(router.urls)),
]
Related
I've setup a Django REST framework project but the api root hasn't been populated with anything eg a users ViewSet and I can't access the expected url with a list of users.
There is one app users, with a custom user model. (and the django project is named api)
main urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('users.urls')),
]
the users app urls.py
from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from users.views import CustomUserViewSet
router = DefaultRouter()
router.register("users", CustomUserViewSet, 'users')
urlpatterns = [
]
urlpatterns += router.urls
users models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
pass
def __str__(self):
return self.username
users serialisers.py
from rest_framework.serializers import ModelSerializer
from .models import CustomUser
class CustomUserSerializer(ModelSerializer):
class Meta:
model = CustomUser
fields = '__all__'
users app views.py
from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from .serializers import CustomUserSerializer
from .models import CustomUser
class CustomUserViewSet(ViewSet):
serializer_class = CustomUserSerializer
queryset = CustomUser.objects.all(
And empty api root at localhost:8000/api/
and 404 error at localhost:8000/api/users/
If you are using just Viewset, you need to implement the actions.
From the docs:
The ViewSet class does not provide any implementations of actions. In
order to use a ViewSet class you'll override the class and define the
action implementations explicitly
You can add a list action like in the example:
from rest_framework.response import Response
class CustomUserViewSet(ViewSet):
serializer_class = CustomUserSerializer
queryset = CustomUser.objects.all()
def list(self, request):
queryset = CustomUser.objects.all()
serializer = CustomUserSerializer(queryset, many=True)
return Response(serializer.data)
Or (maybe what you are looking for) using something like ModelViewSet that already includes implementations for various actions:
class CustomUserViewSet(viewsets.ModelViewSet):
serializer_class = CustomUserSerializer
queryset = CustomUser.objects.all()
In your case, you have to simply replace
class CustomUserViewSet(ViewSet):
with
class CustomUserViewSet(viewsets.ModelViewSet):
I have some error with Rest API when started Django project.
The error is
"raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'api.urls' from '/Users/luba/code/library/library_project/api/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import."
My code:
api/views.py
from rest_framework import generics
from books.models import Book
from .serializers import BookSerializer
class BookAPIView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
api/urls.py
from django.urls import path
from .views import BookAPIView
urlpattens = [
path('', BookAPIView.as_view()),
]
api/serializers.py
from rest_framework import serializers
from books.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'subtitle', 'author', 'isbn')
books/views.py
from django.urls import path
from .views import BookListView
urlpatterns = [
path('', BookListView.as_view(), name='home'),
]
books/views.py
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
Somebody can explain, in which staff problem with my code.Will be appreciate!!!!
It seems like you didn't include your api urls to main urls.py
You can find it at same folder where your settings.py is located.
from django.urls import path, include
from api import urls
urlpatterns = [
path('api/', include(urls.urlpatterns)),
]
This error I am getting while entering http://127.0.0.1:8000/api/student/ this URL
My Database :
posts/models.py
from django.db import models
class Student(models.Model):
lname = models.CharField(max_length=50)
fname=models.CharField(max_length=50)
def __str__(self):
return self.lname
posts/serializers.py(webapp)
from rest_framework import serializers
from . import models
class StudentSerializer(serializers.ModelSerializer):
class Meta:
fields = ('lname','fname',)
model = models.Student
posts\filters.py(webapp)
from django_filters import rest_framework as filters
from .models import Student
class StudentFilter(FilterSet):
total = filters.NumberFilter(name='total')
class Meta:
model = Student
fields = ['lname','fname','total',]#other fields
posts\views.py(webapp)
from rest_framework import generics
from django.db.models import Count
from .models import Post,Student,Exam,Sample
from .serializers import PostSerializer,StudentSerializer,ExamSerializer,SampleSerializer
from django_filters.rest_framework import DjangoFilterBackend
#import django_filters.rest_framework
from django.db import connection
class StudentList(generics.ListAPIView):
serializer_class = StudentSerializer
def get_queryset(self):
return
Student.objects.all().values('fname').annotate(total=Count('fname')).order_by('total')
posts\urls.py(webapp)
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostList.as_view()),
path('<int:pk>/', views.PostDetail.as_view()),
path('student/',views.StudentList.as_view()),
path('exam/',views.ExamList.as_view()),
path('sam/',views.SampleList.as_view())
]
SampleProject(urls.py)
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('posts.urls')),
]
I got output in the shell but I couldn't get the same value in the browser (API)
Settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework.authentication.BasicAuthentication',),
'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated',)
}
models.py
from django.db import models
class Emp(models.Model):
eid = models.IntegerField()
ename = models.CharField(max_length=30)
sal = models.IntegerField()
def __str__(self):
return self.ename
admin.py
from django.contrib import admin
from .models import Emp
class AdminEmp(admin.ModelAdmin):
list_display = ['eid','ename','sal']
admin.site.register(Emp,AdminEmp)
serializers.py
from .models import Emp
from rest_framework import serializers
class EmpSerializer(serializers.ModelSerializer):
class Meta:
model = Emp
fields = ('eid','ename','sal')
views.py
from .serializers import EmpSerializer
from .models import Emp
from rest_framework import viewsets
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import IsAuthenticated
class EmpViewSet2(viewsets.ModelViewSet):
authentication_classes = (BaseAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Emp.objects.all()
serializer_class = EmpSerializer
app level urls.py
from django.conf.urls import url,include
from .views import EmpViewSet2
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('emp_viewset',EmpViewSet2,base_name='emp_viewset2')
urlpatterns = [
url(r'',include(router.urls)) ]
Project level urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('Basic_Authentication_App.urls'))
]
Username and password window
Django Rest Framework window but when i click on this link
"emp_viewset":"http://127.0.0.1:3499/api/emp_viewset/"
it shows like below:
NotImplementedError at /api/emp_viewset/
.authenticate() must be overridden.
You need to write your own authentication back-end. You can see an example from the official django documentation that explains in detail how to implement (i.e. override) the authenticate function.
Of course, if you want to provide your own permissions, you can implement a custom authentication back-end.
Remove below code from views.py:-
authentication_classes = (BaseAuthentication,)
permission_classes = (IsAuthenticated,)
everything will work properly.
and if you want to change permissions than just add in views.py
permission_classes = []
no need to add
authentication_classes
So the
permission_classes
in views.py will override the permission given in settings.py..
Thankyou.
I use django rest framework and have this error:
base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .model or .queryset attribute.
This is my code
urls.py
from django.conf.urls import patterns, include, url
from rest_framework import viewsets, routers
import views
router = routers.SimpleRouter()
router.register(r'book', views.BookViewSet.as_view())
views.py
from django.shortcuts import render_to_response
from mobileapp.models import Book
from rest_framework import generics
from mobileapp.serializers import BookSerializer
class BookViewSet(generics.ListAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
serializers.py
from mobileapp.models import Book
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'url', 'date', 'comment')
Have you google'd error statement?
https://github.com/tomchristie/django-rest-framework/issues/933
http://django-rest-framework.org/api-guide/routers.html#usage
I'v solved my problem. There is code.
urls.py
from django.conf.urls import patterns, include, url
from views import BookList, BookDetail
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^book/$', BookList.as_view(), name='book-list'),
url(r'^book/(?P<pk>\d+)/$', BookDetail.as_view(), name='book-detail'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
views.py
class BookList(generics.ListCreateAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
model = Book
serializer_class = BookSerializer