2017-02-18 23 views
1

我添加了一個名爲'password_confirm'的變量。但是鑑於,django並不知道它。 在html文件中,我手動創建了一個表單。django-我的表單有attrubute'password_confirm',但在我看來不知道

我的形式的代碼:

class UserRegisterForm(forms.Form): 
name = forms.CharField(required=True,) 
family = forms.CharField(required=True) 
username = forms.CharField(required=True) 
email = forms.EmailField(required=True) 
password = forms.CharField(required=True, widget=forms.PasswordInput()) 
password_confirm = forms.CharField(required=True, widget=forms.PasswordInput()) 
type = forms.CharField(max_length=1) 


def clean_password(self, *args, **kwargs): 
    pas1 = self.cleaned_data.get('password') 
    pas2 = self.cleaned_data.get('password_confirm') 
    if pas1 != pas2: 
     raise forms.ValidationError("password and confirmation not matched!") 

    return super(UserRegisterForm, self).clean() 

def clean_email(self): 
    email_qs = User.objects.filter(email=self.cleaned_data['email']) 
    if email_qs.exists(): 
     raise forms.ValidationError("this email already exists!") 

這是我的形式的元素:

<input type="password" name="password_confirm" id="confirm-password" tabindex="8" class="form-control" placeholder="confirm" dir="rtl"/> 

,這是視圖:

def register_view(request): 
if request.user.is_authenticated: 
    return HttpResponseRedirect('/') 

form = UserRegisterForm(request.POST or None) 
if form.is_valid(): 
    user = form.save(commit=False) 
    password = form.cleaned_data['password'] 
    user.set_password(password) 
    user.save() 
    profile = Profile() 
    profile.name = form.cleaned_data['name'] 
    profile.family = form.cleaned_data['family'] 
    profile.name = form.cleaned_data['email'] 
    profile.type = form.cleaned_data['type'] 
    profile.save() 
    login(request, user) 
    return HttpResponseRedirect('/') 
return render(request, 'accounts/signup.html', {'form': form}) 

這是錯誤:在/ KeyError異常register/ 'password_confirm'

有什麼問題?

回答

1

表單域的順序很重要。由於password_confirmclean_password之前定義的password方法password_confirm爲空。 您需要執行密碼檢查clean_password_confirm方法,只需重命名它:

def clean_password_confirm(self, *args, **kwargs): 
    ... 
相關問題