1

我想扩展现有表单,以便在提交时发送电子邮件:

class BaseForm(forms.Form):

    field = forms.CharField()

    def clean(self):
        "do stuff"
        return self.cleaned_data

class MyForm(BaseForm):

    def clean_field(self):
        "do some validation"
        return self.cleaned_data['field']

class MyEmailingForm(MyForm):
    def clean(self):
        super(MyEmailingForm, self).clean()
        send_mail('Form data',
          self.cleaned_data['field'],
          'Form <noreply@myform.co.uk>',
          ["formdata@myform.co.uk"],
          fail_silently=True)

问题是self.cleaned_data['field']无法从超类访问,我得到一个KeyError. 我需要做什么?

编辑

我想我把事情过于简单化了。代码已经更新,我认为问题可能是双重子类化。

4

4 回答 4

1

我相信只将 self.cleaned_data 返回到基类应该有效。

class MyForm(forms.Form):
    field = forms.CharField()

    def clean(self):
        "do stuff"
        return self.cleaned_data

    class MyEmailingForm(MyForm):
        def clean(self):
            super(MyEmailingForm, self).clean()
            send_mail('Form data',
              self.cleaned_data['field'],
              'Form <noreply@myform.co.uk>',
              ["formdata@myform.co.uk"],
              fail_silently=True)
              return self.cleaned_data
于 2013-03-11T12:14:52.873 回答
1

您需要self.cleaned_data从基类和子类方法中返回。

于 2013-03-11T11:56:34.613 回答
0

实际上,self.cleaned_data['field']您在 base 中设置的字段不包含在cleaned_data.

尝试

class MyForm(forms.Form):
    field = forms.CharField()

    def clean(self):
        cd = self.cleaned_data
        "do stuff with cd"
        return cd
于 2013-03-11T12:09:35.093 回答
0

您必须先使用该is_valid()方法。

https://docs.djangoproject.com/en/dev/topics/forms/

于 2013-03-11T12:00:20.320 回答