【问题标题】:Django - Catch argument in Class based FormViewDjango - 基于类的 FormView 中的 Catch 参数
【发布时间】:2012-05-11 02:56:24
【问题描述】:

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

【问题讨论】:

    标签: python django django-generic-views


    【解决方案1】:

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

    Docs

    【讨论】:

    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多