3

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 !!!

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

Comments

0

urls.py

router = routers.DefaultRouter()
router.register(r'users', UsersViewSet, basename ='users')

This happens when there is no queryset attribute in the viewset.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.