2015-01-14 81 views
1

我已經用電子郵件和其他字段擴展了UserCreationForm,這樣我就可以用它的用戶名和電子郵件驗證用戶。使用用戶名和電子郵件驗證用戶

forms.py:

class UserCreationForm(UserCreationForm): 

    class Meta: 
     model = User 
     fields = ('first_name', 'last_name', 'username', 'email',) 

views.py:

def auth_view(request): 
    username = request.POST.get('username','') 
    password = request.POST.get('password','') 
    user = auth.authenticate(username=username, password=password) 

    if user is not None: 
     auth.login(request, user) 
     return HttpResponseRedirect('/') 
    elif: 
     user = auth.authenticate(email=username, password=password) 
     if user is not None: 
      auth.login(request, user) 
      return HttpResponseRedirect('/') 
    else: 
     return HttpResponseRedirect('/accounts/invalid_login') 

HTML:

<form action="/accounts/auth/" method="post"> 
    {%csrf_token%} 

    <label for="name">Email or Username:</label> 
    <input type="text" name="name" id="name" value=""> 
    <label for="password">Password:</label> 
    <input type="password" name="password" id="password" value=""> 

    <input type="submit" value="LOGIN"> 
</form> 

在我試圖從給兩個usernameemail作爲輸入的意見形式爲name,然後檢查用戶名和密碼是否爲aut henticate。如果沒有,則檢查電子郵件和密碼是否通過驗證。但它不工作。我該如何解決這個問題?請請幫助我。謝謝。

回答

2

你需要創建一個認證後端:這裏是我的:

class EmailAuthBackend(ModelBackend): 
    """ 
    Email Authentication Backend 

    Allows a user to sign in using an email/password pair, then check 
    a username/password pair if email failed 
    """ 

    def authenticate(self, username=None, password=None): 
     """ Authenticate a user based on email address as the user name. """ 
     try: 
      user = User.objects.get(email=username) 
      if user.check_password(password): 
       return user 
     except User.DoesNotExist: 
      try: 
       user = User.objects.get(username=username) 
       if user.check_password(password): 
        return user 
      except User.DoesNotExist: 
       return None 

    def get_user(self, user_id): 
     """ Get a User object from the user_id. """ 
     try: 
      return User.objects.get(pk=user_id) 
     except User.DoesNotExist: 
      return None 

然後在您的設置:

AUTHENTICATION_BACKENDS = ('MyApp.backends.EmailAuthBackend',) 

然後創建一個自定義視圖中使用鑑別功能。

+1

請您詳細說明一下。我需要在哪裏保留'認證'後端? – Kakar

+0

@Kakar你可以在MyApp文件夾中創建backends.py ...!還有其他疑問嗎? –

+0

@Raja我是否需要在backends.py中導入任何東西? – Kakar

相關問題