1

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 ?

markwalker_
  • 12,078
  • 7
  • 62
  • 99
john
  • 539
  • 2
  • 9
  • 24

2 Answers2

5

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.

markwalker_
  • 12,078
  • 7
  • 62
  • 99
  • `django.views.generic.View` and `rest_framework.generics.GenericAPIView` are different. (atleast their `response`) – JPG Dec 11 '18 at 04:17
  • 1
    @JPG The `GenericAPIView` inherits `APIView` which in turn inherits django's own `View` so you'll have the `as_view()` method there as well. The responses will no doubt differ because `View` is intended as a standard view, whereas the rest views are designed for API responses. – markwalker_ Dec 11 '18 at 09:25
0

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,

from rest_framework import generics


class DirectView(generics.CreateAPIView):
    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

JPG
  • 82,442
  • 19
  • 127
  • 206