[英]How can I get initial data in CreateView, Django
I use Django class-based views. 我使用基于Django类的视图。 And I have two classes: one for displaying form in the page, and second for handling it:
我有两个类:一个用于在页面中显示表单,第二个用于处理表单:
views.py: 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: full_post.html:
<form action="/addcomment/" method="post" >
{% csrf_token %}
{{ form }}
<button type="submit" >Add comment</button>
</form>
urls: 网址:
url(r'^blog/post/(?P<post_id>\d+)/$', BlogFullPostView.as_view()),
url(r'^addcomment/$', CommentFormView.as_view()),
And in def form_valid
I need to fill field post, which value I have passed in BlogFullPostView
in get_context_data
: initial={'post': self.object}
在
def form_valid
我需要填写字段post,该值是我在BlogFullPostView
中的get_context_data
中get_context_data
: initial={'post': self.object}
But how can I get it in CommentFormView? 但是如何在CommentFormView中获取它?
I have solved it in this way: Firstly, I try to use get_initial
method. 我已经通过以下方式解决了它:首先,我尝试使用
get_initial
方法。 But I it does not return anything. 但是我没有任何回报。 So, I decide to hide auto filled field
post
- I make it as hidden field. 因此,我决定隐藏自动填充字段
post
-我将其设为隐藏字段。 So, then CreateView easily can create Comment object: 因此,然后CreateView可以轻松创建Comment对象:
widgets = {
'content': forms.Textarea(),
'post': forms.HiddenInput(),
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.