Пароль не регистрируется при сохранении нового пользователя в Django с пользовательской моделью пользователя
Когда я пытаюсь зарегистрировать пользователя, адаптируя то, что я узнал из Building a Custom User Model with Extended Fields youtube tutorial, я не могу войти в систему после этого, несмотря на предоставление того же пароля. Однако я могу войти в систему для любого созданного мной пользователя через командную строку. Вот часть views.py
, которая занимается регистрацией пользователей:
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import get_user_model
from django.conf import settings
User = settings.AUTH_USER_MODEL
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from .forms import TodoForm
from .models import Todo
from django.utils import timezone
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'todo/home.html')
def signupuser(request):
if request.method == 'GET':
return render(request, 'todo/signupuser.html', {'form':UserCreationForm()})
else:
if request.POST['password1'] == request.POST['password2']:
try:
db = get_user_model()
user = db.objects.create_user(request.POST['email'], request.POST['username'],
request.POST['firstname'], request.POST['company'], request.POST['mobile_number'],
password=request.POST['password1'])
user.save()
login(request, user)
return redirect('currenttodos')
Пользователь по-прежнему зарегистрирован, но я не могу войти в систему с предоставленным паролем, я не попадаю в currenttodos для всех, кроме пользователя, которого я создал через командную строку ... В чем может быть причина?
Вот моя пользовательская модель пользователя:
models.py
:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class CustomAccountManager(BaseUserManager):
def create_superuser(self, email, user_name, first_name, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(email, user_name, first_name, password, **other_fields)
def create_user(self, email, user_name, first_name, company, mobile_number, password, **other_fields):
if not email:
raise ValueError(('You must provide an email address'))
email = self.normalize_email(email)
user = self.model(email=email, user_name=user_name, first_name=first_name,
company=company, mobile_number=mobile_number, password=password, **other_fields)
user.set_password(password)
user.save()
return user
class Newuser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(('email address'), unique=True)
user_name = models.CharField(max_length=150, unique=True)
first_name = models.CharField(max_length=150, blank=True)
mobile_number = models.CharField(max_length=10)
company = models.CharField(max_length=5)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['user_name', 'first_name', 'mobile_number']
def __str__(self):
return self.user_name
settings.py
AUTH_USER_MODEL = 'todo.NewUser'