Django 2.0:必须使用对象pk或slug调用通用详细视图

时间:2018-08-14 03:22:35

标签: django django-views

因此,我刚刚将更新视图添加到了详细视图。但是,当我在下面添加“编辑”按钮后尝试加载页面时,出现了“通用详细信息视图”错误。发生了什么事?

模板页面:

<td><a href="{% url 'thing:update' thing_id=thing_id%}" class="btn btn-primary" class>Edit</a></td>

urls.py

        path('update/<slug:thing_id>/', ThingUpdateView.as_view(), name='update'),

views.py

    class ThingUpdateView(LoginRequiredMixin, UpdateView):
    model      = ThingUser
    form_class = ThingUserFormSet
    template_name = "thing/update.html"

追踪

File "C:\myapp\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\myapp\lib\site-packages\django\views\generic\base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)

File "C:\myapp\lib\site-packages\django\contrib\auth\mixins.py" in dispatch
  52.         return super().dispatch(request, *args, **kwargs)

File "C:\myapp\lib\site-packages\django\views\generic\base.py" in dispatch
  89.         return handler(request, *args, **kwargs)

File "C:\myapp\lib\site-packages\django\views\generic\edit.py" in get
  189.         self.object = self.get_object()

File "C:\myapp\lib\site-packages\django\views\generic\detail.py" in get_object
  47.                                  % self.__class__.__name__)

Exception Type: AttributeError at /thing/update/8bv4tyrkyy/
Exception Value: Generic detail view ThingUpdateView must be called with either an object pk or a slug.

1 个答案:

答案 0 :(得分:0)

默认情况下,Django使用slug作为Slug url关键字参数。由于您使用的是thing_id,因此需要在视图中使用slug_url_kwarg属性进行设置:

class ThingUpdateView(LoginRequiredMixin, UpdateView):
    model      = ThingUser
    form_class = ThingUserFormSet
    template_name = "thing/update.html"
    slug_url_kwarg = 'thing_id'