2010-05-30 143 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