如何正确定义ModelForm的初始值?

时间:2015-07-14 10:27:51

标签: django django-models

我不知道,我需要征求你的意见。

我的形式很简单:

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ['text','author','news']

我想在DetailView中添加表单并在那里填写此表单:

class NewsDetailView(DetailView):
    model = News
    template_name = 'news/detail.html'

    def get_initial(self):
        return {'news': self.get_object(), 'author': self.request.user}

    def get_context_data(self, **kwargs):
        context = super(NewsDetailView, self).get_context_data(**kwargs)
        context['form'] = CommentForm(initial=self.get_initial())
        return context

    def post(self, request, *args, **kwargs):
        '''
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            comment_form.save()

我不想展示'作者'和新闻。但是,如果我隐藏它们,我就无法获得初始值..

更新:

表单验证后,我需要通过更新页面在模板中返回当前表单实例。我尝试了下一个:

        comment_form = CommentForm(request.POST, request=request)
        if comment_form.is_valid() and comment_form.validate_user():
            comment_form.save()
            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
        else:
            context = super(NewsDetailView,self).get_context_data(**kwargs)
            context['form'] = comment_form
            return self.render_to_response(context)

但没效果。

1 个答案:

答案 0 :(得分:1)

如果您不使用{{ form.author }}{{ form.news }}渲染字段,则表单无法验证。尝试为每个字段使用HiddenInput,您可以通过覆盖表单的__init__方法来执行此操作:

class CommentForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentForm, self).__init__(*args, **kwargs)
        self.fields['author'].widget = forms.HiddenInput()
        self.fields['news'].widget = forms.HiddenInput()

    class Meta:
        model = Comment
        fields = ['text','author','news']