11

在我的页面上,我需要显示帖子详细信息和评论表单以供查看者发表评论。我创建了 2 个通用视图:

# views.py
class PostDetailView (DetailView):
  model = Post
  context_object_name = 'post'
  template_name = 'post.html'

  def get_context_data(self, **kwargs):
    context = super(PostDetailView, self).get_context_data(**kwargs)
    context['comment_form'] = CommentForm()
    return context

class AddCommentView(FormView):
  template_name = 'post.html'
  form_class = CommentForm
  success_url = '/'

  def form_valid(self, form):
    form.save()
    return super(AddCommentView, self).form_valid(form)

  def form_invalid(self, form):
    return self.render_to_response(self.get_context_data(form=form))

detail = PostDetailView.as_view()
add_comment = AddCommentView.as_view()


# urls.py 
....
url(r'^(?P<pk>\d+)/$', view='detail'),
url(r'^(?P<post_id>\d+)/add_comment/$', view='add_comment'),

....

AddCommentView 中会出现错误,因为我没有为评论指定帖子的 ID。如何访问 AddCommentView 中的 post_id?

4

1 回答 1

26

self.kwargs['post_id']self.args[0]包含该值

文档

于 2012-05-01T15:43:35.990 回答