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

时间:2015-12-25 05:30:19

标签: python django django-class-based-views

我使用基于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}中传递的值$greeting = array(); if (!empty($_GET["male"])) $greeting[] = $_GET["male"]; if (!empty($_GET["male"])) $greeting[] = $_GET["male"]; if (count($greeting) > 0) echo "<h1>Welcome, " . implode(" & ", $greeting) . "!</h1>"; else echo "<h1>Who's there?</h1>";

但是如何在CommentFormView中获取它?

1 个答案:

答案 0 :(得分:0)

我已经用这种方式解决了这个问题:首先,我尝试使用get_initial方法。但我不返回任何东西。所以,我决定隐藏自动填充的字段post - 我把它作为隐藏字段。因此,CreateView可以轻松创建Comment对象:

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