Django 中的 Kwargs 和基于类的视图
我搜索过 SO 和 Django 文档,但似乎找不到这个。我正在扩展 django.contrib.comments 应用程序的基本功能,以使用我的 web 应用程序中的自定义权限系统。对于审核操作,我尝试使用基于类的视图来处理评论的基本查询和对其进行权限检查。 (在此上下文中的“EComment”是我的“增强评论”,继承自基本 django Comment 模型。)
我遇到的问题是 comment_id
是传递的 kwarg来自 urls.py 中的 URL。如何从基于类的视图中正确检索此内容?
现在,Django 抛出错误 TypeError: ModRestore() gets正好 1 个参数(给定 0 个)
。代码如下。
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()
I've searched SO and the Django doc and can't seem to be able to find this. I'm extending the base functionality of the django.contrib.comments app to use the custom permission system that's in my webapp. For the moderation actions, I'm attempting to use a class-based view to handle the basic querying of the comment and permission checking on it. ("EComment" in this context is my "enhanced comment", inherited from the base django Comment model.)
The problem I'm having is comment_id
is a kwarg being passed in from the URL in the urls.py. How do I retrieve this properly from a class-based view?
Right now, Django is throwing the error TypeError: ModRestore() takes exactly 1 argument (0 given)
. Code included below.
urls.py
url(r'restore/(?P<comment_id>.+)/
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()
, ModRestore(), name='ecomments_restore'),
views.py
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有使用基于类的视图。您不小心写了
def
而不是class
:可能应该是:
You are not using a class-based view. You accidentally wrote
def
instead ofclass
:should probably be:
另外,您的 url 模式需要如下所示:
also, your url pattern needs to look like: