简体   繁体   中英

AttributeError: type object 'DirectView' has no attribute 'as_view'

here is my views.py code

class DirectView(mixins.CreateModelMixin):
    serializer_class=DirectSerializer
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)
    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)

and my urls.py

path('direct/',DirectView.as_view(),name='direct'),

but whenever i tried to run the server i get an error as

AttributeError: type object 'DirectView' has no attribute 'as_view'

i don't understand what the issue is ?

Your DirectView class must inherit from a View class in Django in order to use as_view .

from django.views.generic import View

class DirectView(mixins.CreateModelMixin, View):

If you're using the rest framework, maybe the inheritance you need here is CreateAPIView or GenericAPIView (with CreateModelMixin ) which is the API equivalent of the View class mentioned above.

If we are looking into the source code of mixins.CreateModelMixin , we could see it's inherited from object ( builtin type ) and hence it's independent of any kind of inheritance other than builtin type .

Apart from that, Mixin classes are special kind of multiple inheritance. You could read more about Mixins here . In short, Mixins provides additional functionality to the class (kind of helper class ).


So, What's the solution to this problem?

Solution - 1 : Use CreateAPIView
Since you are trying to extend the functionality of CreateModelMixin , it's highly recomended to use this DRF builtin view as,




class DirectView():
    serializer_class = DirectSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)



Reference
1. What is a mixin, and why are they useful?
2. Python class inherits object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM