Django Rest Framework Error 404 detail“: ”Not found." - python

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.

Related

Couldnot resolve URL for hyperlinked relationship using view name "snippet-detail"or incorrectly configured the `lookup_field` attribute on this field

ImproperlyConfigured at /snippet/5
Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.
models.py
from email.policy import default
import imp
from tkinter import CASCADE
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight
from django.contrib.auth.models import User
import snippets
# Create your models here.
LEXERS=[item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES=sorted([(item[1][0],item[0]) for item in LEXERS])
STYLE_CHOICES=sorted([(item,item)for item in get_all_styles()])
class Snippet(models.Model):
created=models.DateTimeField(auto_now_add=True)
title=models.CharField(max_length=100,blank=True,default='')
code=models.CharField(max_length=250,default="0")
linenos=models.BooleanField(default=False)
language=models.CharField(choices=LANGUAGE_CHOICES,default='python',max_length=100)
style=models.CharField(choices=STYLE_CHOICES,default='friendly',max_length=100)
owner=models.ForeignKey('auth.User',related_name='snippets',on_delete=models.CASCADE)
class Meta:
ordering=['created']
permissions.py
import imp
from rest_framework import permissions
class IsOwnerReadOnly(permissions.BasePermission):
"""custom permissions to only allow owners of an oject to edit
"""
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
serializers.py
from operator import mod
from numpy import source
from .models import *
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES,STYLE_CHOICES
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model=Snippet
fields = ['url', 'id', 'owner',
'created', 'title', 'linenos', 'language', 'style']
# fields='__all__'
# fields=['id','url','owner']
from django.contrib.auth.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets=serializers.HyperlinkedRelatedField(lookup_field = 'username',many=True,view_name='snippet-details',read_only=True)
owner=serializers.ReadOnlyField(source='owner.username')
class Meta:
model= User
fields=['id','username','snippets','owner']
views.py
from snippets.models import Snippet
from snippets.permissions import IsOwnerReadOnly
from snippets.serializers import SnippetSerializer
from rest_framework import generics
from snippets.permissions import IsOwnerReadOnly
from rest_framework import permissions
class snippet_list(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class snippet_detail(generics.RetrieveUpdateDestroyAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly,IsOwnerReadOnly]
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
########################## authentication purspose #####################################################
from django.contrib.auth.models import User
from .serializers import *
from rest_framework import permissions
class UserList(generics.ListAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly]
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
permission_classes=[permissions.IsAuthenticatedOrReadOnly]
queryset = User.objects.all()
serializer_class = UserSerializer
####################################### using hyperlinking for relationships #################################################################
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
#api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
urls.py(api)
from rest_framework.urlpatterns import format_suffix_patterns
from django.urls import path,include
from snippets import views
from .views import *
urlpatterns=format_suffix_patterns([path('',views.api_root),
path('snippet/',views.snippet_list.as_view(),name='snippet-list'),
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-details'),
path(' ',views.UserList.as_view(),name='user-list'),
path('Users/<int:pk>',views.UserDetail.as_view(),name='user-details'),
])
urls.py(main project)
from django.contrib import admin
# from snippets.urls import *
# from snippets.views import *
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('snippets.urls')),
]
########################## authentication purspose #####################################################
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
I'm new for django but learning and implementing and also sorting errors. But I got stuck with this error for 2 days. I done many changes but still not working .
It appears to me that you misspelled the url name in the urls.py
You have
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-details'),
replace it with
path('snippet/<int:pk>',views.snippet_detail.as_view(),name='snippet-detail')
remove the "s" from the name

AttributeError: type object has no attribute 'get_extra_actions'

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

Django -how to pass value in dynamic url into queryset

I have a dynamic url that will display the same page but with specific data depending on the value that is in the url.
I'm trying to set up a View that will return the filtered data based on the value in the url but i don't know how to pass value in the url into the queryset.
Views.py:
from rest_framework import permissions
from .serializers import ProductSerializer,CategorySerializer
from .models import Product,Category
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
class ProductViewSet(viewsets.ModelViewSet):
queryset=Product.objects.all()
serializer_class= ProductSerializer
class CategoryViewSet(viewsets.ModelViewSet):
queryset=Category.objects.all()
serializer_class= CategorySerializer
class ProductbyCategory(viewsets.ModelViewSet):
categoryid=1
def __init__(self,request,categoryid):
self.categoryid=categoryid
queryset=Product.objects.filter(categoryid=categoryid)
serializer_class= ProductSerializer
Urls.py
from .views import ProductViewSet,CategoryViewSet,ProductbyCategory
from rest_framework import routers
from .serializers import ProductSerializer,CategorySerializer
from .models import Product,Category
router = routers.DefaultRouter()
router.register(r'products', ProductViewSet)
router.register(r'category', CategoryViewSet)
router.register(r'sort-by-category/<int:categoryid>', ProductbyCategory)
urlpatterns = [
path('',include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
Any help would be greatly appreciated
You can override the get_queryset method:
Views.py
class ProductbyCategory(viewsets.ModelViewSet):
serializer_class= ProductSerializer
def get_queryset(self):
categoryid = self.kwargs['categoryid']
return Product.objects.filter(categoryid=categoryid)
# You have to override get_queryset method
class ProductbyCategory(viewsets.ModelViewSet):
serializer_class= ProductSerializer
def get_queryset(self):
categoryid = self.request.query_params.get('categoryid')
queryset=Product.objects.filter(categoryid=categoryid)
return queryset

Could not resolve URL for hyperlinked relationship using view name "usermodel-detail"

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

DRF detail Not found

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.

Categories

Resources