我正在尝试使用在Python 3.4.3上运行的Django REST Framework构建简单的API。但是,drf路由器URL原来是空的:
项目树:
.
├── api
│ ├── profile
│ │ ├── serializers.py
│ │ └── views.py
│ └── urls.py
└── config
├── settings
└── urls.py
来自服务器的响应: (它不包含指向视图的链接!)
GET /api/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{}
./配置/ urls.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
from app_profile.views import ProfileView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="index.html")),
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include("api.urls", namespace='api')),
]
./ API / urls.py:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from api.profile.views import ProfileViewSet
from rest_framework.routers import DefaultRouter
from django.conf.urls import include, url
router = DefaultRouter()
router.register('users', ProfileViewSet, 'user')
urlpatterns = [
url(r'', include(router.urls)),
]
./ API /简档/ views.py:
from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from app_profile.models import Profile
from .serializers import ProfileSerializer
class ProfileViewSet(ViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
./ API /简档/ serializers.py
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.models import User
from app_profile.models import Profile
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
我遇到不同型号的同样问题。我还试图检查路由器变量包含什么:
>>> print(router.urls)
[<RegexURLPattern api-root ^$>, <RegexURLPattern api-root ^\.(?P<format>[a-z0-9]+)/?$>]
>>> print(router.registry)
[('users', <class 'api.profile.views.ProfileViewSet'>, 'user')]
>>>
这是非常令人难以置信的。谁能告诉我我做错了什么?
答案 0 :(得分:2)
如果您从ViewSet继承 - 您需要专门定义类中的方法
对于您的问题,最好从ModelViewSet
导入from rest_framework import viewsets
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer