2012-12-22 60 views
1

我已經爲我的django項目編寫了新的身份驗證後端,但當輸入用戶名或密碼不正確時,我無法在輸出中顯示錯誤消息。如何在django自定義身份驗證後端中有錯誤消息

這裏是我的身份驗證功能代碼:

def authenticate(self,username=None,password=None): 
    try: 
     authService = AuthenticationLocator().getAuthenticationHttpSoap11Endpoint() 
     authRequest = authenticateRequest() 
     authRequest._Username = username 
     authRequest._Password = password 
     authResult = authService.authenticate(authRequest) 

     if authResult._return[0] == 'true': 

      try: 
       user = User.objects.filter(username=username) 
       if len(user) > 0: 
        usr = user[0] 
       else: 
        usr = self.addUser(username) 

#    Correct Login 
       return usr 

      except User.DoesNotExist: 
       return None 

     elif authResult._return[0] == 'error': 
#   Connection Error 
      return None 
     elif authResult._return[0] == 'false': 
#   InCorrect User 
      return None 
    except : 
     return None 

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

我不知道什麼時候我有一個不正確的用戶名和密碼,我應該怎麼編碼。

和我的登錄模板是這樣的:

{% block content %} 
{% if error_message %} 
<p class="errornote">{{ error_message }}</p> 
{% endif %} 
<div id="content-main"> 
    <form action="{{ app_path }}" method="post" id="login-form"> 
     {{ form.non_field_error }} 
     {% csrf_token %} 
     <div> 
      {{ message }} 
     </div> 
     <div class="form-row"> 
      <div class="form_cell"><label for="id_username">{% trans 'Username:' %}</label></div> 
      <div class="form_cell"><input type="text" name="username" id="id_username" /></div> 
     </div> 
     <div class="form-row"> 
      <div class="form_cell"><label for="id_password">{% trans 'Password:' %}</label></div> 
      <div class="form_cell"><input type="password" name="password" id="id_password" /></div> 
      <input type="hidden" name="this_is_the_login_form" value="1" /> 
     </div> 
     <div class="submit-row"> 
      <label>&nbsp;</label><input type="submit" value="{% trans 'Log in' %}" /> 
     </div> 
    </form> 
<script type="text/javascript"> 
document.getElementById('id_username').focus() 
</script> 
</div> 
{% endblock %} 

請儘快;-)

日Thnx 穆罕默德幫我

回答

3

您需要保存的錯誤在你的認證後端:

def authenticate(self,username=None,password=None,errors=[]): 
    ... 
    errors.append('Connection error.') 

然後寫你的AuthenticationForm如在django.contrib.auth.forms中修改了清理方法:

def clean(self): 
    ... 
    errors = [] 
    self.user_cache = authenticate(username=username, password=password, errors=errors) 
    ... 
    raise form.ValidationError(" ".join(errors))