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
Related
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
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
I am a beginner learning the Django RestFramework. I had created this for an blog post page for my project. I looked through different tutorials and posts but couldn't really figure out. Can you help me converting this functional view into a class view? Thanks
from django.http.response import JsonResponse
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework import serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import PostSerializer
from .models import Post,categories
# Create your views here.
#api_view(['GET'])
def apiOverview(request):
api_urls={
'List':'/article-list/',
'Detail View':'/article-detail/<str:pk>/',
'Create':'/article-create/',
'Update':'article-update/<str:pk>/',
'Delete':'/article-delete/<str:pk>/',
}
return Response(api_urls)
#api_view(['GET'])
def articleList(request):
articles=Post.objects.all()
serializers=PostSerializer(articles,many=True)
return Response(serializers.data)
#api_view(['GET'])
def articleDetail(request,pk):
articles=Post.objects.get(id=pk)
serializers=PostSerializer(articles,many=False)
return Response(serializers.data)
#api_view(['POST'])
def articleCreate(request):
serializers=PostSerializer(data=request.data)
if serializers.is_valid():
serializers.save()
return Response(serializers.data)
#api_view(['POST'])
def articleUpdate(request,pk):
articles=Post.objects.get(id=pk)
serializers=PostSerializer(instance=articles,data=request.data)
if serializers.is_valid():
serializers.save()
return Response(serializers.data)
#api_view(['DELETE'])
def articleDelete(request, pk):
articles=Post.objects.get(id=pk)
articles.delete()
return Response('The item has been deleted')
from rest_framework import generics
class PostList(generics.ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
urls.py
urlpatterns = [
path('',PostList.as_view()),
path('<int:pk>',PostDetail.as_view())
]
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.
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.