2015-11-28 75 views
0

我有一個自定義用戶模型的應用程序「主頁」。我可以註冊新用戶並在我的數據庫中查看。Django自定義用戶模型驗證不起作用

settings.py

AUTH_USER_MODEL = 'homepage.User' 

models.py

from django.db import models 
from django.contrib.auth.models import AbstractUser 

class User(AbstractUser): 
    phone_number = models.CharField(max_length=15, default='') 
    birthday = models.DateField(blank=True, null=True) 

class Meta: 
    db_table = 'auth_user' 

views.py

from django.contrib import auth 
from django.contrib.auth import get_user_model 

def authentication(request): 
    username = request.POST.get('username', '') => one 
    password = request.POST.get('password', '') => 1111 (not 1111 but hash) 
    user = auth.authenticate(username=username, password=password) 

    if user is not None: 
     auth.login(request, user) 

用戶永遠是無。 我可以從數據庫中這樣獲取:

User = get_user_model() 
user = User.objects.get(username='one') 
print(user.username) => one 
print(user.password) => 1111 (not 1111 but hash) 

但我無法登錄如何使它工作?

編輯: 可能是錯誤的形式?

forms.py

from django.contrib.auth.forms import UserCreationForm 
from django.db import models 
from django.contrib.auth import get_user_model 
MyUser = get_user_model() 

class RegistrationForm(UserCreationForm): 
first_name = forms.CharField() 
last_name = forms.CharField() 
username = forms.CharField() 
password1 = forms.CharField(widget=forms.PasswordInput, 
          label="Password")   
password2 = forms.CharField(widget=forms.PasswordInput, 
          label="Confirm password") 
email = forms.EmailField(widget=forms.EmailInput) 
birthday = forms.DateField(widget=extras.SelectDateWidget(years=YEARS)) 
phone_number = forms.CharField() 
captcha = CaptchaField() 

def save(self, commit = True): 
    user = MyUser.objects.create_user(self.cleaned_data['username']) 
    user.email = self.cleaned_data['email'] 
    user.first_name = self.cleaned_data['first_name'] 
    user.last_name = self.cleaned_data['last_name'] 
    user.birthday = self.cleaned_data['birthday'] 
    user.phone_number = self.cleaned_data['phone_number'] 
    user.set_password('password2') 

    if commit: 
     user.save() 

    return user 

回答

0

其實一個問題是在forms.py:

user.set_password('password2') 

我應該保存的密碼這樣的:

user.set_password(self.cleaned_data['password2']) 

而且它現在是好的。

2

如果user.password值是1111,那麼你原來存儲在某種程度上平原測試值; Django將始終散列密碼以進行比較,因爲存儲的值也應該被散列。

確保您最初設置的密碼爲user.set_password,或創建用戶模型User.objects.create_user

+0

實際上它打印的內容如下:!shgKxtqOpu4lqUAPGFmTcDqho96auPUyKnvOmYkF。如果我保存這樣的密碼,它將打印1111:user.password = self.cleaned_data ['password2'](僅用於測試) – tack