网址

时间:2016-03-06 10:49:40

标签: python django django-rest-framework

在学习Django休息框架时,我在/ tasks / 1 错误时出现了 AssertionError

使用名为" pk"的URL关键字参数调用预期视图TaskDetail。修复您的网址,或者在视图上正确设置.lookup_field属性。

我的model.py

class Task(models.Model):
    owner=models.ForeignKey('auth.User',related_name='tasks')
    completed=models.BooleanField(default=False)
    title=models.CharField(max_length=100)
    description=models.TextField()

serializer.py

class TaskSerializer(serializers.ModelSerializer):

class Meta:
    model = Task
    read_only=('owner.username',)
    fields=('title','description','completed','owner.username')

permission.py

class IsOwnerOrReadOnly(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method is SAFE_METHODS:
            return True

        return obj.owner==request.user

views.py

class TasksMixins(object):
    queryset = Task.objects.all()
    serializer_class=TaskSerializer
    permission_classes=(IsOwnerOrReadOnly,)

    def pre_save(self,obj):
        obj.owner=self.request.user

class TaskList(TasksMixins,ListCreateAPIView):
    pass

class TaskDetail(TasksMixins,RetrieveUpdateDestroyAPIView):
    pass

Urls.py

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
    url(r'^tasks/(?P<id>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')
]

回溯

Traceback (most recent call last):
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 286, in get
    return self.retrieve(request, *args, **kwargs)
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 56, in retrieve
    instance = self.get_object()
  File "/home/amogh/PycharmProjects/env_1.9/local/lib/python2.7/site-packages/rest_framework/generics.py", line 93, in get_object
    (self.__class__.__name__, lookup_url_kwarg)
AssertionError: Expected view TaskDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

当我导航到链接时,我收到此错误

非常感谢任何帮助......谢谢你的推荐

error image

1 个答案:

答案 0 :(得分:2)

如果您想通过'pk'定位,只需重命名id - &gt; pk到你的url.py:

url(r'^tasks/(?P<pk>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')

如果你想要通过pk之外的其他字段进行定位,你必须调整url.py,view.py和serializer.py来精确查找一个lookup_field(可以是嵌套的),例如,它可能适合你

url.py:

url(r'^tasks/(?P<owner__username>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail')

view.py:

class TasksMixins(object):
    queryset = Task.objects.all()
    serializer_class=TaskSerializer
    permission_classes=(IsOwnerOrReadOnly,)
    lookup_field = 'owner__username'

serializer.py

class TaskSerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(slug_field='username',many=False, read_only=True)
    class Meta:
        model = Task
        fields='__all__'
        lookup_field = 'owner__username'