Kwargs and class-based views in Django
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>.+)/$', 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()
You are not using a class-based view. You accidentally wrote def
instead of class
:
def ECommentModerationApiView(object):
...
def ModRestore(ECommentModerationApiView):
should probably be:
class ECommentModerationApiView(object):
...
class ModRestore(ECommentModerationApiView):
also, your url pattern needs to look like:
url(r'restore/(?P<comment_id>.+)/$', ModRestore.as_view(), name='ecomments_restore'),
精彩评论