Django - 基于类的FormView中的Catch参数

时间:2012-05-01 15:39:17

标签: python django django-generic-views

在我的页面上,我需要显示帖子详细信息和评论表单,供观看者发表评论。我创建了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?

1 个答案:

答案 0 :(得分:19)

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

Docs