如何在 Django 的 CreateView 中获取初始数据

How can I get initial data in CreateView, Django

我使用基于 Django class 的视图。我有两个 classes:一个用于在页面中显示表单,第二个用于处理它:

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 中我需要填写字段 post,我在 BlogFullPostView 中传递的值在 get_context_data 中:initial={'post': self.object}

但是如何在 CommentFormView 中获取呢?

我是这样解决的: 首先,我尝试使用get_initial方法。但我没有 return 任何东西。因此,我决定隐藏自动填充字段 post - 我将其设为隐藏字段。那么,那么CreateView就可以轻松创建Comment对象了:

widgets = {
            'content': forms.Textarea(),
            'post': forms.HiddenInput(),
        }