Django:' ContactView'对象没有属性'形式'

时间:2017-01-14 22:37:35

标签: django django-forms django-views

我尝试按照本教程(https://hellowebapp.com/news/introduction-to-class-based-views/)进行了观察:

class ContactView(FormView):
    form_class = ContactForm
    success_url = reverse_lazy('index')
    template_name = 'app/contact.html'

    def form_valid(self, form):
        contact_name = self.form.cleaned_data['contact_name']
        contact_email = self.form.cleaned_data['contact_email']
        form_content = self.form.cleaned_data['content']

        template = get_template('contact_template.txt')
        context = Context({
            'contact_name': contact_name,
            'contact_email': contact_email,
            'form_content': form_content
        })
        content = template.render(context)

        email = EmailMessage(
            'New contact form submission',
             content,
             'Your website ' + '',
             ['youremail@gmail.com'],
             headers={'Reply-To': contact_email}
        )
        email.send()
        return super(ContactView, self).form_valid(form)

但是,当我提交表单时,我收到以下错误: 'ContactView' object has no attribute 'form'

该错误似乎与此部分有关:

  contact_name = self.form.cleaned_data['contact_name']
  contact_email = self.form.cleaned_data['contact_email']
  form_content = self.form.cleaned_data['content']

其中'形式'是一个未解决的参考。

如何修复此错误?任何帮助深表感谢! 我使用的是Python 3.5和Django 1.9。

1 个答案:

答案 0 :(得分:3)

那应该是form而不是self.form(因为表单实例作为参数传递给函数)。

def form_valid(self, form):
    contact_name = form.cleaned_data['contact_name']
    contact_email = form.cleaned_data['contact_email']
    form_content = form.cleaned_data['content']
    ...