2015-11-28 80 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