I am working on a project that returns some metrics from a text.
The user is to enter the text in a textbox and the results are displayed to the user.
My serializers.py
from rest_framework.serializers import ModelSerializer
from .models import Entryt
class CreateEntrySerializer(ModelSerializer):
class Meta:
model = Entryt
fields = ('text',)
class EntryDetailSerializer(ModelSerializer):
class Meta:
model = Entryt
fields = ('sentence_count', 'flesch_ease', 'flesch_grade', 'smog', 'linsear', 'text_standard')
lookup_field = 'pk'
views.py
from rest_framework.generics import CreateAPIView, RetrieveAPIView
from .serializers import EntryDetailSerializer, CreateEntrySerializer, Entryt
class CreateEntryView(CreateAPIView):
model = Entryt
serializer_class = CreateEntrySerializer
queryset = Entryt.objects.all()
class ResultView(RetrieveAPIView):
serializer_class = EntryDetailSerializer
queryset = Entryt.objects.all()
urls.py
from django.conf.urls import url
from .views import ResultView, CreateEntryView
urlpatterns = [
url(r'^', CreateEntryView.as_view(), name='create'),
url(r'^result/(?P<pk>[0-9]+)/$', ResultView.as_view(), name='result'),
]
http://localhost:8000/flesch/result/2/ url like this show's nothing though there is an item with that id in the db.
How do I go about fixing this and any tips on making the code better would be great.
Related
I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list.
models.py
from django.db import models
class EmployeeModel(models.Model):
EmpID = models.IntegerField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100)
Salary = models.FloatField()
class Meta:
verbose_name = 'employeetable'
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import EmployeeModel
from .serializers import EmployeeSerialize
class EmployeeTable(APIView):
def get(self,request):
emp_obj = EmployeeModel.objects.all()
empserializer = EmployeeSerialize(emp_obj,many=True)
return Response(empserializer.data)
serializers.py
from rest_framework import serializers
from .models import EmployeeModel
class EmployeeSerialize(serializers.ModelSerializer):
class Meta:
model = EmployeeModel
fields = '__all__'
urls.py
from django.contrib import admin
from django.urls import path, include
from .views import EmployeeTable, transformer_list
urlpatterns = [
path('display/',EmployeeTable.as_view()),
]
The table has 5 rows. It is not empty.
I want to serialize all 5 rows
I have also created the same but in my case, it worked see the below images
See my serializer
See my models below
and my output is here below
I think there are some issue at your code or some mistake can be there can you please provide full information
I have a small web app, and I'm trying to develop an API for it. I'm having an issue with a model I have called Platform inside of an app I have called UserPlatforms. The same error: AttributeError: type object 'UserPlatformList' has no attribute 'get_extra_actions'
models.py:
class Platform(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='platform_owned',
on_delete=models.CASCADE,
default=10)
PLATFORM_CHOICES = [platform_x, platform_y]
platform_reference = models.CharField(max_length=10, choices=PLATFORM_CHOICES, default='platform_x')
platform_variables = models.JSONField()
api/views.py
from .serializers import PlatformSerializer
from rest_framework import generics, permissions
from userplatforms.models import Platform
class UserPlatformList(generics.ListCreateAPIViewAPIView):
queryset = Platform.objects.all()
permisson_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = PlatformSerializer
api/serializer.py
from rest_framework import serializers
from userplatforms.models import Platform
class PlatformSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Platform
fields = '__all__'
api/urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms')
router.register(r'userfiles/', views.UserFileList, "userfiles")
router.register(r'users/', views.UserList, "user")
urlpatterns = [
path("^", include(router.urls))
]
You cannot add generic Views in routers.
So remove this line:
router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms')
and update urlpatterns to:
urlpatterns = [
path('userplatforms/', views.UserPlatformList, name='userplatforms'),
path("^", include(router.urls))
]
change class PlatformSerializer(serializers.HyperlinkedModelSerializer): to class PlatformSerializer(serializers.ModelSerializer):
api/views.py
from .serializers import PlatformSerializer
from rest_framework import generics, permissions
from userplatforms.models import Platform
class UserPlatformList(generics.ListCreateAPIViewAPIView):
queryset = Platform.objects.all()
permisson_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = PlatformSerializer
for the UserPlatformList inheritance, ListCreateAPIViewAPIView should be ListCreateAPIView
If you are using mixins to create the viewset, then it should be like
from .serializers import PlatformSerializer
from rest_framework import generics, permissions, viewsets
from userplatforms.models import Platform
class UserPlatformList(generics.ListModelMixin, viewsets.GenericViewSet):
queryset = Platform.objects.all()
permisson_classes = [permissions.IsAuthenticatedOrReadOnly]
serializer_class = PlatformSerializer
This way router can be used to set the urlpatterns
api/urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'userplatforms/', views.UserPlatformList, 'userplatforms')
router.register(r'userfiles/', views.UserFileList, "userfiles")
router.register(r'users/', views.UserList, "user")
urlpatterns = router.urls
Hi im trying to Hyperlink my API but cant seem to get it to work. This is my serializers.py:
from rest_framework import serializers
from api.models import *
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UserModel
fields = '__all__'
depth = 1
class BlogSerializer(serializers.HyperlinkedModelSerializer):
posts = serializers.HyperlinkedRelatedField(
many=True, view_name='blogs-detail', read_only=True)
class Meta:
model = BlogModel
fields = ['url', 'id', 'title', 'body', 'posts']
This is my views.py
class UserViewset(viewsets.ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = UserSerializer
class BlogViewset(viewsets.ModelViewSet):
queryset = BlogModel.objects.all()
serializer_class = BlogSerializer
And this is my urls.py:
from django.urls import path, include
from api.views import *
from rest_framework import routers
router = routers.DefaultRouter()
router.register('users', UserViewset, basename='users')
router.register('blogs', BlogViewset, basename='blogs')
urlpatterns = [
path('', include(router.urls)),
path('post/<int:pk>/', PostView, name='post'),
#path('update-post/<str:pk>/', updatePost, name='post'),
]
Ive tried to follow the django rest tutorial but i still cant seem to get it to work. Im just staring out learingn the rest Framework. Thanks for your feedback in advance!
remove basename from router.register
django is not able to find the generated default detail view for that.
https://www.django-rest-framework.org/apiguide/serializers/#hyperlinkedmodelserializer
I have a django project and I am using Django Rest Frameowkr. I setup up a model, serializer, view, and url for a users model. I have the urls file. I want to passing in something like a username when the api url is called. I currently have it setup to have a primary key so when I enter a primary key it works. I want to switch it to username. I also want the serializer query to return the user object iwth the usename I pass in.
I am using Djangos standard User object from django.contrib.auth.models
Here is the code I have
Urls.py
from django.urls import path
from django.contrib.auth.models import User
from .views import UserListView, UserDetailsView
from .views import ProfileListView, ProfileDetailsView
from .views import RoleListView, RoleDetailsView
urlpatterns = [
path('user/', UserListView.as_view()),
path('user/<pk>', UserDetailsView.as_view()),
]
serializer.py file
from rest_framework import serializers
from django.contrib.auth.models import User
from users.models import Profile, Role
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'is_staff', 'last_login')
Views.py file
from rest_framework.generics import ListAPIView, RetrieveAPIView
from django.contrib.auth.models import User
from users.models import Profile, Role
from .serializers import UserSerializer, ProfileSerializer, RoleSerializer
class UserListView(ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetailsView(RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
Specify the lookup_field in UserDetailsView and change the urls pattern in urls.py as below
# urls.py
urlpatterns = [
path('user/', UserListView.as_view()),
path('user/<username>', UserDetailsView.as_view()),
]
# views.py
class UserDetailsView(RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'username'
When i go to localhost:8000/api/create i get this:
https://imgur.com/a/7DT48VQ
views.py:
from rest_framework import viewsets
from rest_framework.generics import (
ListAPIView,
RetrieveAPIView,
CreateAPIView,
# DestroyAPIView,
# UpdateAPIView
)
from articles.models import Article
from .serializers import ArticleSerializer
class ArticleListView(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetailView(RetrieveAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleCreateView(CreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
urls.py:
from django.urls import path, include
from .views import ArticleListView, ArticleDetailView, ArticleCreateView
urlpatterns = [
path('', ArticleListView.as_view()),
path('create/', ArticleCreateView.as_view()),
path('<pk>', ArticleDetailView.as_view()),
]
models.py:
from django.db import models
# Article Model
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
def __str__(self):
return self.title
I'm on windows 10, using python 3.7.1 i don't know what else to write but i'm writing these words so this thing will let me post, ignore this.