【问题标题】:How can I get initial data in CreateView, Django如何在 Django 的 CreateView 中获取初始数据
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-05
      • 2018-07-09
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2012-10-29
      相关资源
      最近更新 更多