django rest_framework viewset没有路由

时间:2015-06-15 05:43:35

标签: django django-rest-framework

我用django rest_framework开始了一个新的django应用程序。有一件事很奇怪 - 当我从快速入门尝试这个例子时它工作得很好:我在http://localhost:8000/users/得到一条我可以查询的路线。但它并不适用于我自己的应用程序,尽管它可能是最小的。我的路线http://localhost:8000/listings/不可用,我没有收到任何错误。我使用的是django 1.8.2和djangorestframework 3.1.3。

settings.py:

#...
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_swagger',
    'debug_toolbar',
    'listing',
)
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ] 
}
#...

urls.py:

from rest_framework import routers, serializers, viewsets
from listing.models import Listing


class ListingSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Listing
        fields = ('description',)


class ListingViewSet(viewsets.ViewSet):
    queryset = Listing.objects.all()
    serializer_class = ListingSerializer


router = routers.DefaultRouter()
router.register(r'listings', ListingViewSet)

urlpatterns = router.urls

models.py:

from django.db import models


class Listing(models.Model):
    description = models.TextField()

修改

错误:

Page not found (404)
Request Method:     GET
Request URL:    http://127.0.0.1:8000/listings/

Using the URLconf defined in djangoway.urls, Django tried these URL patterns, in this order:

    ^__debug__/
    ^$ [name='api-root']
    ^\.(?P<format>[a-z0-9]+)$ [name='api-root']

The current URL, listings/, didn't match any of these.

修改 Answered my question并删除了代码,因为它没有什么奇怪的。

1 个答案:

答案 0 :(得分:0)

我应该使用ModelViewSet:

class ListingViewSet(viewsets.ModelViewSet):
                              ^^^^^

感谢xordoquy在我打开的issue中指出它。