Reputation: 325
I have an application 'homepage' with custom user model. I can register new user and see it in my DB.
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 is always None. I may retrieve it from db like this:
User = get_user_model()
user = User.objects.get(username='one')
print(user.username) => one
print(user.password) => 1111 (not 1111 but hash)
But I can't log in. How to make it work?
EDIT: maybe something wrong in forms?
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
Upvotes: 0
Views: 792
Reputation: 325
Actually a problem was in forms.py:
user.set_password('password2')
I should save password like this:
user.set_password(self.cleaned_data['password2'])
And it's ok now.
Upvotes: 0
Reputation: 599600
If the value of user.password
is 1111, then you've originally stored the value in plain test somehow; Django will always hash passwords for comparison, because the stored value should be hashed too.
Make sure you set the password originally with user.set_password
, or create the User model with User.objects.create_user
.
Upvotes: 3