Django 类视图中的 get_initial 方法不起作用

1 投票
1 回答
3368 浏览
提问于 2025-04-17 21:47

我正在尝试在一个 FormView 中使用 get_initial 方法,想要预先填充“主题”这个字段,让它显示“批发商感兴趣”的内容,但这个方法没有成功。如果有关系的话,我使用的是 Django 1.5 和 Python 2.7。以下是我的代码。我是不是漏掉了什么步骤?

class ContactView(FormView):
    """
    ContactForm is a ModelForm
    """
    template_name = 'core/contact-us.html'
    form_class = ContactForm
    success_url = reverse_lazy('products:index')
    initial = {'subject': 'I am interested in making a wholesale purchase'}


    def get_initial(self):
        """
        Returns the initial data to use for forms on this view.
        """
        return self.initial

    def get_form_kwargs(self):
        kwargs = {'initial': self.get_initial()}
        return kwargs

    def form_valid(self, form):
        cd = form.cleaned_data
        contact = Contact.objects.create(**form.cleaned_data)
        if contact:
            print 'contact created'
        else:
            print 'not created'
        if contact is not None:
            # send contact email
            msg = contact_email(name=cd['name'], email=cd['email'], subject=cd['subject'], message=cd['message'])
            msg.send()
            # Add success message 
            msg = 'Your contact email has been successfully sent.  We look forward to speaking with you.'
            messages.info(self.request, msg)
        return super(ContactView, self).form_valid(form)

编辑

我去掉了 get_initialget_form_kwargs,但还是没有成功。这里是我的 Form 的代码,如果这有帮助的话。我需要以某种方式把我想放入 Forminitial 连接上吗?谢谢你的帮助!

class ContactForm(forms.ModelForm):

    class Meta:
        model = Contact  
        fields = ('name', 'email', 'subject', 'message',)
        widgets = {
            'message': forms.Textarea(attrs={'cols': 20, 'rows': 20}),
        }

1 个回答

4

与其使用 FormView,不如试试 CreateView。它是 FormView 的一个子类,专门处理你的实际模型。

另外,你是怎么在模板中显示表单的?如果你手动一个一个字段去处理,可能会漏掉初始值的显示。

撰写回答