python - 网址处的 Django AssertionError

标签 python django django-rest-framework

在学习 Django rest framework 时,我得到了一个 AssertionError at/tasks/1 错误

预期 View TaskDetail 将使用名为“pk”的 URL 关键字参数调用。修复您的 URL 配置,或正确设置 View 上的 .lookup_field 属性。

我的模型.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()

序列化器.py

class TaskSerializer(serializers.ModelSerializer):

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

权限.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

View .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

网址.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

最佳答案

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

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

如果您想通过 pk 以外的其他字段作为目标,则必须调整 url.py、view.py 和 serializer.py 来精确定位查找字段(可以嵌套),例如,它可能适合您.

网址.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'

序列化器.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'

关于python - 网址处的 Django AssertionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825941/

相关文章:

python - django.contrib.auth.views.login 什么都不做,为什么?

python - 解析 DRF 请求主体 : TypeError the JSON object must be str, 而不是 'bytes'

python - 如何使用 django Rest 框架解析多部分表单数据中的多个文件?

python - 跨模块共享单例

python - 使用默认为节点名称的节点标签绘制 networkx 图

python - 按位置切片 MultiIndex pandas DataFrame

python - 使用自定义文本绘制 x 轴点

django - 在 Django 的管理界面中添加换行符和标题

python - 谁能告诉我django的延迟加载和事务吗?

python - 性能突然从 1024 字节下降到 1025 字节