0

這是我的登記表:Django的ifequal不工作

class RegistrationForm(forms.Form): 
    username = forms.CharField(label='Username', max_length=30) 
    email = forms.EmailField(label='Email') 
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput()) 
    password2 = forms.CharField(label='Password (Again)', widget=forms.PasswordInput()) 

def clean_password2(self): 
    if 'password1' in self.cleaned_data: 
     password1 = self.cleaned_data['password1'] 
     password2 = self.cleaned_data['password2'] 
     if password1 == password2: 
      return password2 
    raise forms.ValidationError('Passwords do not match.') 

def clean_username(self): 
    username = self.cleaned_data['username'] 
    if not re.search(r'^\w+$', username): #checks if all the characters in username are in the regex. If they aren't, it returns None 
     raise forms.ValidationError('Username can only contain alphanumeric characters and the underscore.') 
    try: 
     User.objects.get(username=username) #this raises an ObjectDoesNotExist exception if it doesn't find a user with that username 
    except ObjectDoesNotExist: 
     return username #if username doesn't exist, this is good. We can create the username 
    raise forms.ValidationError('Username is already taken.') 

,這是我的模板:

{% if form.errors %} 

    {% for field in form %} 
     {% if field.label_tag == "Password (Again)" %} 
      <p>The passwords which you entered did not match.</p> 
     {% else %} 
      {{ field.label_tag }} : {{ field.errors }} 
     {% endif %} 
    {% endfor %} 
{% endif %} 

我基本上想說

The passwords which you entered did not match. 

如果Django中返回一個錯誤爲password2字段。我沒有在RegistrationForm說

password2 = forms.CharField(label='Password (Again)' 

但Django的,可直接到達else語句,當它執行線

{{ field.label_tag }} : {{ field.errors }} 

,當我檢查了Web瀏覽器,它說

Password (Again) : This field is required. 

所以

field.label_tag 

確實等於

"Password (Again)" 

對不對?我的

if field.label_tag == "Password (Again)" 

聲明是不是評估爲真?

回答

1

你在瀏覽器中看到的不是field.label_tag真的是什麼。

其實field.label_tag是這樣的(你可以看看HTML源代碼):

<label for="id_password2">Password (Again):</label> 

引述一位偉人機制(Django documentation):

{{} field.label_tag }該字段的標籤包裹在適當的 HTML標記中。

此代碼應工作:

{% if field.label_tag == '<label for="id_password2">Password (Again):</label>' %} 
etc 

現在,很明顯,沒有人願意寫這樣的代碼。使用HTML代碼的字符串?來吧,奈傑爾,你比這更好!

這裏是更好的辦法:

{% if field.name == 'password2' %} 
etc 

事實上,我認爲甚至有一個更好的方式來處理表單錯誤。您可以閱讀文檔here