2014-10-04 76 views
0

我有一個ModelForm用戶可以使用它來更改他們的first_name,last_name和email。Modelform忽略required = True

我有一個乾淨的函數來檢查用戶是否試圖將電子郵件更改爲已經註冊的電子郵件。

我的代碼:

class DjangoUserForm(ModelForm): 
    def __init__(self, *args, **kwargs): 
     self.helper = FormHelper() 
     self.helper.layout = Layout(
      Field('username', type="hidden"), 
      Field('first_name'), 
      Field('last_name'), 
      Field('email'), 
     ) 
     super(DjangoUserForm, self).__init__(*args, **kwargs) 
     self.fields['first_name'].required = True 
     self.fields['last_name'].required = True 
     self.fields['email'].required = True 

    class Meta: 
     model = User 
     fields = ['first_name', 'last_name', 'email', 'username'] 


    def clean_email(self): 
     email = self.cleaned_data['email'] 
     return email 

    def clean(self): 
     cleaned_data = super(DjangoUserForm, self).clean() 

     email = self.cleaned_data['email'] 
     username = self.cleaned_data['username'] 

     if User.objects.exclude(username=username).filter(email=email).exists(): 
      if not self._errors.has_key('email'): 
       from django.forms.util import ErrorList 
       self._errors['email'] = ErrorList() 
      self._errors['email'].append('Email is used by another user') 


     return cleaned_data 

功能的工作原理,但如果我嘗試保存形式與空電子郵件字段我得到這個錯誤:KeyError at /accounts/user/change/'email'。我有self.fields['email'].required = True,我期待django提出一個「必需」的錯誤。任何人都知道我做錯了什麼?

回答

1

試試這個:

def clean(self): 
    cleaned_data = super(DjangoUserForm, self).clean() 
    if not self._errors: 
     email = self.cleaned_data['email'] 
     username = self.cleaned_data['username'] 

     if not User.objects.exclude(username=username).filter(email=email).exists(): 
      return cleaned_data 
     else:  
      from django.forms.util import ErrorList 
      self._errors['email'] = ErrorList() 
      self._errors['email'].append('Email is used by another user') 
+0

完美!謝謝! – 2014-10-04 11:12:07

+0

不客氣,兄弟。 – 2014-10-04 11:14:46

相關問題