Class-based Django API only GET method. It's possible? - django

I'm building a class-based only GET method API with Django and Rest Framework. However, looking on internet, it seems to be impossible to do that.
Here is my urls.py:
from django.urls import path, include
from rest_framework import routers
from . import views
api_router = routers.DefaultRouter()
api_router.register(r"get_foo_id", views.GetFooIdViewSet)
urlpatterns = [
path( "", include(api_router.urls)),
]
views.py
from app.models import *
from app.serializers import *
from rest_framework import viewsets
from django_filters.rest_framework import DjangoFilterBackend
class GetFooIdViewSet(viewsets.ModelViewSet):
queryset = Foos.objects.all()
serializer_class = FoosSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['foo_id']
It's really impossible?

You can allow only GET(list) requests in urls.py.
Try to do it:
path('your_path/', views.GetFooIdViewSet.as_view({
'get': 'list'
})),

Related

'Access-Control-Allow-Origin' issue even though I've set up the settings.py correctly?

amateur developer here. Trying to follow this tutorial, where in the settings.py I have
CORS_ALLOWED_ORIGINS = ['http://localhost:8080']
as per the video.
However, when I try to access the server from my front-end, I get the error
Access to XMLHttpRequest at 'http://127.0.0.1:8000/engine' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Appreciate there are many similar posts on SO, but I couldn't understand why I'm having this issue whereas the guy who made the tutorial does not. This is the rest of my code:
models.py
from django.db import models
from django.utils import timezone
import datetime
class Engine(models.Model):
date = models.DateField(default=datetime.datetime(2024,1,1))
serializers.py
from rest_framework import serializers
from .models import Engine
class EngineSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Engine
fields = ('id', 'date')
views.py
from django.shortcuts import render
from .models import Engine
from .serializers import EngineSerializer
from rest_framework import viewsets
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
class EngineViewSet(viewsets.ModelViewSet):
authentication_classes = (BasicAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Engine.objects.all()
serializer_class = EngineSerializer
urls.py
from django.contrib import admin
from django.urls import path, include
from backend_app.views import EngineViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('engine', EngineViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls))
]
'http://localhost:8080' and 'http://127.0.0.1:8080' are not the same. They may point to exactly the same code and functions, but they are different for such matter.
Put both options inside the list:
CORS_ALLOWED_ORIGINS = ['http://localhost:8080', 'http://127.0.0.1:8000']
I'm not sure about ports, though.
Some more help is to found HERE.

Converting to using URL router is causing a ImproperlyConfigured exception

I have been working through the Django Rest Framework tutorial and on the very last step I am encountering the error:
Exception Type: ImproperlyConfigured.
Exception Value:
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.
When trying to view either /settings/ or /users/ (visiting any user pages yields the same exception but with "user-detail" in place of "snippet-detail") as well as any specific indices of them, etc. All that works is root and login.
All my code thus far has been working fine and I'm very confused as to why copy-pasting from the tutorial would yield such catastrophic results
In comparing my snippets files with those available on the tutorial's repo I have not been able to find any significant difference (all that I've found is inconsistencies in whitespace). That being said, here is the code I'm using.
snippets/views.py:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from rest_framework import generics, permissions
from django.contrib.auth.models import User
from snippets.permissions import IsOwnerOrReadOnly
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import renderers
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import permissions
from rest_framework import viewsets
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `retrieve` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class SnippetViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly]
#action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
snippets/urls.py:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from snippets import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet,basename="snippets")
router.register(r'users', views.UserViewSet,basename="users")
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]
snippets/serializers.py:
from django.contrib.auth.models import User
from rest_framework import serializers
from snippets.models import Snippet
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(
view_name='snippet-highlight', format='html')
class Meta:
model = Snippet
fields = ('url', 'id', 'highlight', 'owner', 'title', 'code',
'linenos', 'language', 'style')
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(
many=True, view_name='snippet-detail', read_only=True)
class Meta:
model = User
fields = ('url', 'id', 'username', 'snippets')
tutorial/urls.py:
"""tutorial URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('snippets.urls')),
]
urlpatterns += [
path('api-auth/', include('rest_framework.urls')),
]
Router was being passed the wrong base names (plural forms of snippet and user rather than singular). Thanks to #IainShelvington for the answer in the comments!
To elaborate:
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from snippets import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet,basename="snippets")
router.register(r'users', views.UserViewSet,basename="users")
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]
should have been
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from snippets import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet,basename="snippet")
router.register(r'users', views.UserViewSet,basename="user")
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]

Setting up router with APIView and viewset in Django Rest Framework

It's my first question on Stackoverflow !
I'm new to Django and following some tutorials.
I'm trying to understand if there is a way to set up the routing of an API from different view classes like APIView and viewsets.ModelViewSet (please tell me if I do not use the good wording)
In views I have :
from rest_framework import viewsets
from post.models import UniquePost
from .serializers import UniquePostSerializers
from rest_framework.views import APIView
class UniquePostViewSet(viewsets.ModelViewSet):
serializer_class = UniquePostSerializers
queryset = UniquePost.objects.all()
class FileUploadView(APIView):
some code here but no queryset nor serialized data...and no model
In urls I have :
from post.api.views import UniquePostViewSet
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from post.api.views import FileUploadView
router = DefaultRouter()
router.register('UniquePost', UniquePostViewSet, base_name='uniquepostitem')
router.register('demo', FileUploadView, base_name='file-upload-demo')
urlpatterns = router.urls
But it seems that I can register FileUploadView this way. Because I don't have a queryset to render.
I have : AttributeError: type object 'FileUploadView' has no attribute 'get_extra_actions'
I realized that (well I think) that I can use APIView for FileUploadView (and add ".as_view()) but I think I have to rewrite UniquePostViewSet using APIView as well and defining exactly what I want to see in details like POST, PUT etc...
My question is : Is there a way to use DefaultRouter router.register and insert a view that inherit from APIView (and a view that inherit from viewsets.ModelViewset) at the same time ?
Hope all of this is clear and thank you so much for your help !!!
Something like this should work.
from post.api.views import UniquePostViewSet
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from post.api.views import FileUploadView
router = DefaultRouter()
router.register('UniquePost', UniquePostViewSet, base_name='uniquepostitem')
urlpatterns = [
path('demo',FileUploadView.as_view(),name='demo'),
]
urlpatterns += router.urls
urls.py
router = routers.DefaultRouter()
router.register(r'users', UsersViewSet, basename ='users')
This happens when there is no queryset attribute in the viewset.

can i use DefaultRouter with CreateAPIView in django rest?

when I try to add my CreateAPIView to router.register it rise TypeError exception:
File "/home/denys/.virtualenvs/buddha_test/lib/python3.5/site-packages/rest_framework/routers.py", line 281, in get_urls
view = viewset.as_view(mapping, **route.initkwargs)
TypeError: as_view() takes 1 positional argument but 2 were given
But if I add url directly to urlpatterns it works!
The resone is that I whant to see link in API Root:
enter image description here
So quation is can I write something like this:
urls.py
from django.conf.urls import url, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'clients-list', views.ClientList)
router.register(r'managers-list', views.ManagerList)
router.register(r'clients', views.CleintCreate, base_name='create')
urlpatterns = [
url(r'^', include(router.urls)),
]
views.py
from .models import Client, Manager
from .serializers import ClientSerializer, ManagerSerializer
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.generics import CreateAPIView
from rest_framework.decorators import detail_route
class ClientList(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated, )
queryset = Client.objects.all()
serializer_class = ClientSerializer
class ManagerList(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticated, )
#
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
class CleintCreate(CreateAPIView):
model = Client
serializer_class = ClientSerializer
permission_classes = (AllowAny,)
Instead of implementing CreateAPIView, you can create GenericViewSet and also inherit CreateModelMixin:
views.py:
# ...
class ClientCreate(CreateModelMixin, GenericViewSet):
model = Client
serializer_class = ClientSerializer
permission_classes = (AllowAny,)
And then in your urls.py it's just the same:
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'clients-list', views.ClientList)
router.register(r'managers-list', views.ManagerList)
router.register(r'clients', views.ClientCreate, base_name='create')
urlpatterns = [
url(r'^', include(router.urls)),
]

How to accommodate APIView & ViewSet views in urls.py

How would one write a urls.py file to accommodate views created from APIView and ViewSet.
entity.views.py
from .models import Entity
from .serializers import EntitySerializer
class EntityViewSet(DefaultsMixin, ListCreateRetrieveUpdateViewSet):
"""
"""
queryset = Entity.objects.all()
serializer_class = EntitySerializer
filter_fields = ('id', 'entity_number')
class PersonProfileList(APIView):
"""
person profile
"""
def get(self, request, format=None):
pass
entity.urls.py
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
entity_router = DefaultRouter()
entity_router.register(r'entity', views.EntityViewSet)
urlpatterns = [
url(r'profile/$', views.PersonProfileList.as_view(), name='profile_list'), # Is this correct?
url(r'profile/(?P<pk>[0-9]+)/$', views.PersonProfileList.as_view(), name='profile_detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
main urls.py
from django.conf.urls import include, url
from django.contrib import admin
from entities.urls import entity_router, urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^entities/', include(entity_router.urls)), #This I know works
url(r'^entities/', include(urlpatterns.url)), # This throws errors
]
What is the best way to accommodate both types of Views in the same URL file and have them appear under one /entity unlike now when am getting two /entity entries. Also, once I get into the /entity page in the browsable API, how do I make the /entity/profile viewable since now it only shows /entity. See images for guide.
Root Page
Entities Page