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

时间:2014-03-11 14:12:35

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

我正在尝试在get_initial中使用FormView来预填充“主题”字段以使“批发商感兴趣”文字,但它无效。如果重要的话,我正在使用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的粘贴。我是否需要附加initial以便以某种方式将Form添加到class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('name', 'email', 'subject', 'message',) widgets = { 'message': forms.Textarea(attrs={'cols': 20, 'rows': 20}), } 中?谢谢你的帮助!

{{1}}

1 个答案:

答案 0 :(得分:2)

不要使用FormView,请尝试CreateView。它是FormView的子类,负责处理您的实际模型。

另外,如何在模板中显示表单?如果您手动浏览所有字段,则可能未显示初始值。