我在一個項目上第一次使用Django REST框架,並且我正在努力應對一個特定的部分。該項目是一個問題跟蹤器類型的應用程序,它使用django_comments
來允許對問題進行評論。我現在在它上面創建一個API以允許創建一個移動應用程序。努力讓django_comments與Django REST框架一起工作
我創建了以下串行:
from django.contrib.auth.models import User
from todolist.models import Project, Issue
from rest_framework import serializers
from django_comments.models import Comment
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'first_name', 'last_name')
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'owner')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
class IssueSerializer(serializers.HyperlinkedModelSerializer):
comments = CommentSerializer(many=True)
class Meta:
model = Issue
這是我的項目範圍urls.py
,在那裏我定義路線:
from django.conf.urls import patterns, include, url
from todolist.views import HomeTemplateView, UserViewSet, ProjectViewSet, IssueViewSet, CommentViewSet
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'projects', ProjectViewSet)
router.register(r'issues', IssueViewSet)
router.register(r'comments', CommentViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'projectile.views.home', name='home'),
# url(r'^projectile/', include('projectile.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# Comments
(r'^comments/', include('django_comments.urls')),
# Login
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
# Logout
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login', {'login_url': '/accounts/login/'}),
# To-do list
url(r'^projects/', include('todolist.urls')),
# Home page
url(r'^$', HomeTemplateView.as_view(
template_name="todolist/home.html",
)),
# Router URLs
url(r'^api/', include(router.urls)),
# REST framework auth URLs
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', obtain_auth_token),
# API docs
url(r'^docs/', include('rest_framework_swagger.urls'))
)
我看到下面的錯誤,當我運行一個試圖獲得所有評論的測試:
ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "contenttype-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
此外,當我獲取n問題,它不包括評論。
現在,這個錯誤在我看來是在提取評論時,無法將評論與其父項進行匹配。我有experienced similar problems when using Tastypie in the past,我不確定如何用DRF解決它。
你可以發佈你的urls.py文件。 – levi 2015-02-06 15:47:15
@levi做了 – 2015-02-06 15:50:09
你有一個名爲'contenttype'的序列化程序嗎? – levi 2015-02-06 15:52:44