2010-07-13 126 views
0

我正在使用標準身份驗證表單。它的清潔方法是這樣的:奇怪的驗證錯誤消息

def clean(self): 
    username = self.cleaned_data.get('username') 
    password = self.cleaned_data.get('password') 

    if username and password: 
     self.user_cache = authenticate(username=username, password=password) 
     if self.user_cache is None: 
      raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive.")) 
     elif not self.user_cache.is_active: 
      raise forms.ValidationError(_("This account is inactive.")) 

    # TODO: determine whether this should move to its own method. 
    if self.request: 
     if not self.request.session.test_cookie_worked(): 
      raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")) 

    return self.cleaned_data 

我的登錄表單:

<form method="post" action="{% url django.contrib.auth.views.login %}"> 
    <table> 
     {% if form.errors %} 
      <tr class="form-errors"> 
       <td> 
        <ol> 
         {% for error in form.errors %} 
          <li>{{ error }}</li> 
         {% endfor %} 
        </ol> 
       </td> 
      </tr> 
     {% endif %} 

而不是確認的消息,我得到:

如果用戶名和傳球不正確或帳戶已停用「 1. __all__
如果沒有給出密碼:」1. password
如果沒有給出用戶名:」1. username
如果兩者都沒有給出: 「1. username 2. password
沒有用戶名不正確

編輯消息: 如果我改變

   <td> 
        <ol> 
         {% for error in form.errors %} 
          <li>{{ error }}</li> 
         {% endfor %} 
        </ol> 
       </td> 

到:

{{form.errors}}

我收到ie即__all__ and beneath it "Account inactive"。如何獲取消息? 任何想法?

回答

2

試試這個。 form.errors是一本字典,就像每一本字典一樣,你可以閱讀關鍵和價值。鍵是字段或__all__',值是您正在查找的錯誤消息。

{% if form.errors %} 
<tr> 
    {% for k, v in form.errors.items %} 
    <td>{{k}}</td> 
    <td>{{v}}</td> 
    {% endfor %} 
</tr> 
{% endif %} 

編輯

如果您wan't選擇特定領域的錯誤類型:

{% if form.errors %} 
    {% for k, v in form.errors.items %} 
     <tr> 
      {% ifequal k 'password' %} 
       <td>Password</td> 
       {% else %} 
        {% ifequal k 'username' %} 
         <td>Username</td> 
         {% else %} 
          <td>Other</td> 
      {% endifequal %}{% endifequal %}     
      <td>{{v}}</td> 
     </tr> 
    {% endfor %} 
{% endif %} 

或ifequal選擇'__all__'

+0

現在要選擇只採取'__all__'錯誤:/ – muntu 2010-07-13 19:10:34

+0

編輯我的答案 – crivateos 2010-07-13 19:49:53