Reputation: 3213
I have the model named Artist and I want expose this model with Django Rest Framework to create an API and this data can be consumed.
I've created a class based view in artists/views.py named ArtistViewSet
#CBV for rest frameworks
from rest_framework import viewsets
class ArtistViewSet(viewsets.ModelViewSet):
model = Artist
I also have an url named api/ in the urls.py file (view third url named api/) which the user could access to the view above mentioned.
# coding=utf-8
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
from rest_framework import routers
from artists.views import ArtistViewSet
#I create a router by default
router = routers.DefaultRouter()
#Register the model 'artists' in ArtistViewSet
router.register(r'artists', ArtistViewSet)
urlpatterns = patterns('',
(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
url(r'^admin/', include(admin.site.urls)),
#Include url api/ with all urls of router
url(r'^api/', include(routers.urls)),
)
When I go to my browser and type http://localhost:8000/api/ I get this message error:
What did can be happened me?
Upvotes: 1
Views: 248
Reputation: 41719
In Django REST framework 2.4+ (including 3.0+), the model
attribute for views has been deprecated and removed. This means that you should be defining your view as
from rest_framework import viewsets
class ArtistViewSet(viewsets.ModelViewSet):
queryset = Artist.objects.all()
Which should give you the result you are expecting. Now, you asked in the comments
I cannot understand the role of base_name. I mean, this base name is the url that I've created? My viewset
ArtistViewSet
does not have aqueryset
attribute, due to this, according to documentation, it's necessary put the base_name argument, but i don't know how to do it.
The base_name
that can be optionally defined when registering a ViewSet
is used when naming the automatically generated routes. By default, the format is [base]-list
and [base]-detail
, where [base]
is the base_name
that can be defined. When you do not specify your own base_name
, it is automatically generated based on the model name. As the queryset
method must be defined for ViewSet
instances, this is where the model (and later model name) is retrieved. As you did not provide the queryset
argument, Django REST framework triggers an error because it cannot generate a base_name
.
To quote from the documentation on routers
Note: The
base_name
argument is used to specify the initial part of the view name pattern.
The documentation goes on to further explain exactly why you are getting the issue, even including an example, and how to fix it.
Upvotes: 3