我在尝试以我创建的形式提交评论时遇到此错误。
这是包含CommentForm
的类视图和返回HttpResponseRedirect
的方法,仅用于测试目的:
class GetPostView(TemplateView):
template_name = 'blog/post.html'
def get(self, request, id):
return render(request, self.template_name, {
'post': Post.objects.get(pk = id),
'comments': Comment.objects.filter(post = id),
'form': CommentForm()
})
def comment(self, request):
return HttpResponseRedirect(request.path)
在这里,urls.py
:
app_name = 'blog'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name = 'index'),
url(r'^categories/$', views.CategoriesView.as_view(), name = 'categories'),
url(r'^post/(?P<id>[0-9]+)/$', views.GetPostView.as_view(), name = 'post'),
url(r'^post/(?P<id>[0-9]+)/comment$', views.GetPostView.comment)
]
而且,与标题一样,当我提交表单时,会出现错误:
必须使用GetPostView实例作为第一个参数调用未绑定方法comment()(改为获取WSGIRequest实例)
我是Django的新手,我找不到任何其他类似的情况来帮助我。
我会在我的问题中提出解决方案,因为丹尼尔值得信任和积分。在他回答之后,我通过这样做解决了这个问题:
"""
GetPostView
"""
class GetPostView(TemplateView):
"""
Render the view for a specific post and lists its comments
"""
template_name = 'blog/post.html'
def get(self, request, id):
return render(request, self.template_name, {
'post': Post.objects.get(pk = id),
'comments': Comment.objects.filter(post = id).order_by('-created_at'),
'form': CommentForm()
})
def write_comment(request, post_id):
"""
Write a new comment to a post
"""
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
post = Post.objects.get(pk = post_id)
post.n_comments += 1
post.save()
comment = Comment()
comment.comment = request.POST['comment']
comment.created_at = timezone.now()
comment.modified_at = timezone.now()
comment.post_id = post_id
comment.user_id = 2
comment.save()
else:
form = CommentForm()
return redirect(reverse('blog:post', args = (post_id,)))
新的url
:
app_name = 'blog'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name = 'index'),
url(r'^categories/$', views.CategoriesView.as_view(), name = 'categories'),
url(r'^post/(?P<id>[0-9]+)/$', views.GetPostView.as_view(), name = 'post'),
url(r'^post/(?P<post_id>[0-9]+)/comment$', views.write_comment)
]
尽管有许多事情要做,以使其完美,例如只有在用户登录时允许评论,这是一个良好的开端。
答案 0 :(得分:1)
基于类的观点不会像那样工作; url需要指向从as_view
返回的类本身,它们会自动调度到get或post方法,并且您根本无法路由到任意方法。
为comment
视图定义单独的函数或类。