【发布时间】:2016-03-31 08:08:54
【问题描述】:
我使用 Django 基于类的视图。我有两个类:一个用于在页面中显示表单,第二个用于处理它:
views.py:
class CommentFormView(CreateView):
form_class = AddCommentForm
model = Comment
success_url = '/'
def form_valid(self, form):
form.instance.author = self.request.user
form.instance.post = ????
return super(CommentFormView, self).form_valid(form)
class BlogFullPostView(BlogBaseView, DetailView):
model = Post
template_name = 'full_post.html'
pk_url_kwarg = 'post_id'
context_object_name = 'post'
def get_context_data(self, **kwargs):
context = super(BlogFullPostView, self).get_context_data(**kwargs)
context['form'] = AddCommentForm(initial={'post': self.object})
return context
full_post.html:
<form action="/addcomment/" method="post" >
{% csrf_token %}
{{ form }}
<button type="submit" >Add comment</button>
</form>
网址:
url(r'^blog/post/(?P<post_id>\d+)/$', BlogFullPostView.as_view()),
url(r'^addcomment/$', CommentFormView.as_view()),
在def form_valid 中我需要填写字段帖子,我在BlogFullPostView 中传递了get_context_data 中的值:initial={'post': self.object}
但是如何在 CommentFormView 中获取呢?
【问题讨论】:
标签: python django django-class-based-views