Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework - cannot get the class based view right

Here is my codes:

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ( 'username', 'email')


class AllListingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Listing
        fields = ('name', 'desc', 'thumbnail', 'office_no', 'mobile_no', 'email', 'web ')

views.py

class UserViewSet(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class AllListing(generics.ListCreateAPIView):
    queryset = Listing.objects.all()
    serializer_class = AllListingSerializer

urls.py

urlpatterns = patterns('',
                        url(r'^$', apiview.UserViewSet),
                        url(r'^listings/$', apiview.AllListing),
                        )

But when i goto the base url it shows

init() takes 1 positional argument but 2 were given

and when i goto '/listings/' url, it give me 404 Page Not Found, but I have few listings in the db.

I am pretty new in django. I can't figure out what wrong with them. I am using Django 1.7.1 in virtualwrappr, python 3.4.

like image 278
dev-jim Avatar asked Nov 14 '14 05:11

dev-jim


2 Answers

You should call .as_view() for each API view:

urlpatterns = patterns('',
                       url(r'^$', apiview.UserViewSet.as_view()),
                       url(r'^listings/$', apiview.AllListing.as_view()),
                      )

Also, consider using REST framework's Routers which provide you with a simple, quick and consistent way of wiring your view logic to a set of URLs.

like image 98
alecxe Avatar answered Nov 13 '22 08:11

alecxe


This happened to me when I extended generics.GenericAPIView in stead of viewsets.GenericViewSet in my custom ViewSet class.

Pretty obvious but easy to miss.

like image 25
Sander van Leeuwen Avatar answered Nov 13 '22 10:11

Sander van Leeuwen