error with serialization in django rest framework - python

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

Related

Datatables| Django, sorting, paging and searching with DRF

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)),
]

Rest API . Help to change ListView

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)),
]

Django Rest Api Annotate group by Filter showing Error?

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)

Circular import error when I open the Django server

When I open the server(Django) I get this error: "The included URLconf 'admin.urls' 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."
I have found out that by removing .views import from urls.py I fix the issue. So I think the problem is inside views.py.
App urls.py
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('/api', include('crud.urls')),
]
views.py
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import User
from .serializers import UserSerializer
class UserView(APIView):
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response({"users": users})
serializer.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
name = serializers.CharField(max_length=255)
email = serializers.EmailField()
password = serializers.CharField(max_length=255)
disease = serializers.CharField(max_length=255)
logo = serializers.TextField()
crud urls.py
Here, the issue is at the second line: if I remove that line I fix the error
from django.urls import path
from .views import UserView
app_name='crud'
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('users/', UserView.as_view()),
]
Please add error trace for better understanding of the issue.
Meanwhile try changing this:
path('/api', include('crud.urls'))
to:
path('api/', include('crud.urls')),
and
from .views import UserView
to:
from crud import views
urlpatterns = [
path('users/', views.UserView.as_view()),
]

I am creating a Basic authentication in Django Rest Framework in Django 2.1 version.But it shows '.authenticate() must be overridden' error

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.

Categories

Resources