在CreateView中为Django ModelForm设置字段值

时间:2014-06-28 00:37:23

标签: python django forms views modelform

我需要通过我的ModelForm的CreateView设置我的Django模型中的BooleanField的值。但出于某种原因,在form_valid()中设置它并不起作用。

这是我的模特:

class Feedback(models.Model):
    was_satisifed = models.BooleanField(
        help_text='Returns true if the user exits the process early.',
        default=False)

以下是我的观点:

class FeedbackActionMixin(object):
    model = Feedback
    form_class = FeedbackForm

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.was_satisfied = True
        return super(FeedbackActionMixin, self).form_valid(form)

表单提交,但是" was_satisfied"值保留默认值False。我错过了什么?

2 个答案:

答案 0 :(得分:0)

如果内存服务,则在已发布数据后调用form_valid。您可以尝试覆盖mixin上的post方法:

class FeedbackActionMixin(object):
    model = Feedback
    form_class = FeedbackForm

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        if form.is_valid():
            form.was_satisfied = True
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

答案 1 :(得分:0)

这是我最终做的事情,虽然在forms.py而不是views.py

class SuccessfulFeedbackForm(FeedbackFormMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(SuccessfulFeedbackForm, self).__init__(*args, **kwargs)
        self.fields['was_satisifed'].initial = True


class UnsuccessfulFeedbackForm(FeedbackFormMixin, forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(UnsuccessfulFeedbackForm, self).__init__(*args, **kwargs)
        self.fields['was_satisifed'].initial = False