我目前正在使用django-rest-framewok版本处理Django项目。 我面临一个奇怪的问题,说意外的关键字参数命名版本。
views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = ScreenShotUser.objects.all()
serializer_class = UserSerializer
def getMe(self,request):
user = ScreenShotUser.objects.get(pk=request.user.id)
return Response(user)
项目url.py
router = routers.DefaultRouter()
router.register(r 'users', views.UserViewSet)
urlpatterns = [
url(r '^api/(?P<version>(v1|v2))/accounts/', include('Accounts.urls')),
]
和帐户应用程序的urls.py
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^me/$', views.getMe),
]
当我致电http://127.0.0.1:8000/api/v1/accounts/me/时 我得到了这样的错误
TypeError at /api/v1/accounts/me/
getMe() got an unexpected keyword argument 'version'
Request Method: GET
Request URL: http://127.0.0.1:8000/api/v1/accounts/me/
Django Version: 1.9.4
Exception Type: TypeError
Exception Value:
getMe() got an unexpected keyword argument 'version'
Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py in get_response, line 147
Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
Python Version: 3.5.1
Python Path:
['/Working_repo/screenshot/ScreenShot',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django_contrib_requestprovider-1.0.1-py3.5.egg',
'/Working_repo/screenshot/ScreenShot',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
Server time: Mon, 28 Mar 2016 13:12:54 +0000
Django专家请给我一些我遗漏的提示。 TIA
修改 我有解决方案概念形式尚旺的答案,这将是我的解决方案
@api_view(['GET'])
def getMe(request, version):
user = ScreenShotUser.objects.get(pk=request.user.id)
result = UserSerializer(user).data
return Response(result)
答案 0 :(得分:4)
如果您在网址中定义了(?P<version>(v1|v2))
,则表示您的views.py方法需要参数version
。但是您的getMe
方法没有将其作为参数,因此错误。轻松修复将删除网址定义中的命名参数。
修改强>
你应该看看django doc about named group,在python中(?P<name>pattern)
表示一个名为group的正则表达式。如果你在django url定义中有这个,那就意味着你将一个参数传递给views.py方法。我不认为你的views.py方法正在使用version
参数,所以你不应该在url中定义。你这样做:
url(r '^api/v1|v2/accounts/', include('Accounts.urls')),
如果您无法删除version
参数,因为其他一些方法确实需要它,只需在getMe
方法中定义它并且不要将它用于任何事情:
def getMe(self, request, version):
user = ScreenShotUser.objects.get(pk=request.user.id)
return Response(user)
在how url dispatcher is working上阅读django doc中的更多详细信息。