【问题标题】:Kwargs and class-based views in DjangoDjango 中的 Kwargs 和基于类的视图
【发布时间】:2011-01-23 11:39:18
【问题描述】:

我搜索了 SO 和 Django 文档,但似乎无法找到它。我正在扩展 django.contrib.cmets 应用程序的基本功能,以使用我的 web 应用程序中的自定义权限系统。对于审核操作,我尝试使用基于类的视图来处理评论的基本查询和对其的权限检查。 (本文中的“EComment”是我的“增强评论”,继承自基本的 django 评论模型。)

我遇到的问题是comment_id 是从 urls.py 中的 URL 传入的 kwarg。如何从基于类的视图中正确检索它?

现在,Django 正在抛出错误 TypeError: ModRestore() takes exactly 1 argument (0 given)。代码如下。

urls.py

url(r'restore/(?P<comment_id>.+)/$', ModRestore(), name='ecomments_restore'),

views.py

def ECommentModerationApiView(object):

    def comment_action(self, request, comment):
        """
        Called when the comment is present and the user is allowed to moderate.
        """
        raise NotImplementedError

    def __call__(self, request, comment_id):
        c = get_object_or_404(EComment, id=comment_id)
        if c.can_moderate(request.user):
            comment_action(request, c)
            return HttpResponse()
        else:
            raise PermissionDenied

def ModRestore(ECommentModerationApiView):
    def comment_action(self, request, comment):
        comment.is_removed = False
        comment.save()

【问题讨论】:

    标签: django django-views django-class-based-views


    【解决方案1】:

    您没有使用基于类的视图。你不小心写了def 而不是class

    def ECommentModerationApiView(object):
    ...
    def ModRestore(ECommentModerationApiView):
    

    应该是:

    class ECommentModerationApiView(object):
    ...
    class ModRestore(ECommentModerationApiView):
    

    【讨论】:

      【解决方案2】:

      另外,您的 url 模式需要如下所示:

      url(r'restore/(?P<comment_id>.+)/$', ModRestore.as_view(), name='ecomments_restore'),
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-08
        • 2016-07-28
        • 2022-01-07
        • 2012-12-28
        • 2018-05-14
        • 1970-01-01
        相关资源
        最近更新 更多