Django Forms Clean_Data键错误

时间:2015-05-16 21:15:39

标签: python django forms

目前我遇到一个奇怪的问题,我似乎无法解决。

我有一个用于注册用户的表单。我的Django 1.7.4项目中有自定义用户模型。一切正常,但最近,如果已经存在具有相同电子邮件地址的用户,则网站崩溃。

这是跟踪:

Environment:


Request Method: POST
Request URL: http://mysite.dbz.dev/purchase/step1/Business

Django Version: 1.7.4
Python Version: 2.7.9
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_summernote',
 'usercp',
 'clickatell',
 'downloadcenter',
 'purchaseorder',
 'paypalrestsdk',
 'import_export',
 'debug_toolbar')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'mysite.middleware.AutoLogout',
 'mysite.middleware.LocationChecker')


Traceback:
File "/home/bs/envs/main-page/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/vhosts/main-page/purchaseorder/views.py" in step1
  194.         if form.is_valid():
File "/home/bs/envs/main-page/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  162.         return self.is_bound and not bool(self.errors)
File "/home/bs/envs/main-page/lib/python2.7/site-packages/django/forms/forms.py" in errors
  154.             self.full_clean()
File "/home/bs/envs/main-page/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  353.         self._clean_fields()
File "/home/bs/envs/main-page/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields
  371.                     value = getattr(self, 'clean_%s' % name)()
File "/var/www/vhosts/main-page/usercp/forms.py" in clean_email2
  343.         email = self.cleaned_data["email"]

Exception Type: KeyError at /purchase/step1/Business
Exception Value: 'email'

这些是我的清洁方法:

   def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            Customer.objects.get(email=email)
        except Customer.DoesNotExist:
            return email

        raise forms.ValidationError(
            self.error_messages['duplicate_email'],
            code='duplicate_email',
        )

    def clean_email2(self):
        email = self.cleaned_data["email"] #<!--- THIS IS THE LINE WHERE IT FAILES / ERRORS
        email2 = self.cleaned_data["email2"]

        if email != email2:
            raise forms.ValidationError(
                self.error_messages['no_mail_match'],
                code='no_mail_match'
            )
        return email2

当有现有用户时,是否有人理解为什么会失败?在我看来,cleaning_data被一个对象取代。但这对我没有意义。

1 个答案:

答案 0 :(得分:0)

在表单中,如果要根据多个字段进行清理,则必须使用clean方法而不是clean_field方法:

def clean(self): # change this line
    email = self.cleaned_data.get("email")
    email2 = self.cleaned_data.get("email2")

    if email != email2:
        raise forms.ValidationError(
            self.error_messages['no_mail_match'],
            code='no_mail_match'
        )
    return email2

<强> - 编辑 -

使用Michael B评论

进行编辑