2010-05-30 95 views
4

Django新手在這裏。在Django自定義登錄

我寫了簡化的登錄表單,它需要電子郵件和密碼。如果提供了電子郵件和密碼,它會很好用,但如果缺少任何一個,我會得到KeyError異常。根據django的文檔,這絕不應該發生:

默認情況下,每個Field類都假定該值是必需的,所以如果您傳遞一個空值 - 無或空字符串(「」) - 然後清理()會引發ValidationError異常

我試圖爲字段(clean_email和clean_password)編寫我自己的驗證器,但它不起作用(即我得到KeyError異常)。我究竟做錯了什麼?

class LoginForm(forms.Form): 
    email = forms.EmailField(label=_(u'Your email')) 
    password = forms.CharField(widget=forms.PasswordInput, label=_(u'Password')) 

    def clean_email(self): 
     data = self.cleaned_data['email'] 
     if not data: 
      raise forms.ValidationError(_("Please enter email")) 
     return data 

    def clean_password(self): 
     data = self.cleaned_data['password'] 
     if not data: 
      raise forms.ValidationError(_("Please enter your password")) 
     return data 

    def clean(self): 
     try: 
      username = User.objects.get(email__iexact=self.cleaned_data['email']).username 
     except User.DoesNotExist: 
      raise forms.ValidationError(_("No such email registered")) 
     password = self.cleaned_data['password'] 

     self.user = auth.authenticate(username=username, password=password) 
     if self.user is None or not self.user.is_active: 
      raise forms.ValidationError(_("Email or password is incorrect")) 
     return self.cleaned_data 
+2

與django一起發貨的['django.contrib.auth.forms.AuthenticationForm'](http://github.com/jacobian/django/blob/master/django/contrib/auth/forms.py#L54)是非常簡單和強大。如果你沒有迫切的需求,那就用它吧。 – miku 2010-05-30 16:21:47

+0

我通過電子郵件和密碼進行身份驗證,而不是用戶名和密碼。 – mgs 2010-05-30 16:24:52

+1

相反看看這樣的事情:[在Django中使用電子郵件地址登錄](http://www.davidcramer.net/code/224/logging-in-with-email-addresses-in-django.html) – miku 2010-05-30 16:29:29

回答

4

你可以利用Django的內置的方式在你的settings.py設置 AUTHENTICATION_BACKENDS覆蓋認證是如何發生的

這裏是我的EmailAuthBackend:

#settings.py 
AUTHENTICATION_BACKENDS = (
    'auth_backend.auth_email_backend.EmailBackend', 
    'django.contrib.auth.backends.ModelBackend', 
) 

#auth_email_backend.py 
from django.contrib.auth.backends import ModelBackend 
from django.forms.fields import email_re 
from django.contrib.auth.models import User 

class EmailBackend(ModelBackend): 
    """ 
    Authenticate against django.contrib.auth.models.User 
    """ 

    def authenticate(self, **credentials): 
     return 'username' in credentials and \ 
      self.authenticate_by_username_or_email(**credentials) 

    def authenticate_by_username_or_email(self, username=None, password=None): 
     try: 
      user = User.objects.get(email=username) 
     except User.DoesNotExist: 
      try: 
       user = User.objects.get(username=username) 
      except User.DoesNotExist: 
       user = None 
     if user: 
      return user if user.check_password(password) else None 
     else: 
      return None 

    def get_user(self, user_id): 
     try: 
      return User.objects.get(pk=user_id) 
     except User.DoesNotExist: 
      return None 

#forms.py 
#replaces the normal username CharField with an EmailField 
from django import forms 
from django.contrib.auth.forms import AuthenticationForm 

class LoginForm(AuthenticationForm): 
    username = forms.EmailField(max_length=75, label='Email') 
    next = forms.CharField(widget=forms.HiddenInput) 

希望幫助!

+0

David Cramer的腳本比我的效率更高,因爲他使用用戶名語句中的if'@'來設置查找kwargs。我採用了他的方法。 – Brandon 2011-03-17 19:20:50