#Models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
# User Model For registration ---------------------------------------------------------------------------
class StudentUserManager(BaseUserManager):
def create_user(self, name,email,gender, password,picture=None, ):
"""
Creates and saves a User with the given email and password.
"""
if not gender:
raise ValueError('User must have a gender')
if not email:
raise ValueError('Users must have an email address')
user = self.model(
name = name,
email=self.normalize_email(email),
gender = gender,
picture = picture
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, name, email, gender, password,picture=None,):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
name = name,
email=self.normalize_email(email),
gender = gender,
picture = picture,
password=password,
)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class StudentUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
GENDER_CHOICE = (
('Male','Male'),
('Female','Female'),
('Other','Other')
)
name = models.CharField(max_length=100, default='Open Blog Forum User')
gender = models.CharField(max_length=10,null=True, blank=False, choices = GENDER_CHOICE)
picture = models.ImageField(upload_to='Student Pictures', blank = True, null=True)
creationTime = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = StudentUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name','gender']
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
# User Model Ends ---------------------------------------------------------------------------------------
#Views.py
def userLogin(request):
if request.method=='POST':
try:
email=request.POST['email']
password = request.POST['password']
if StudentUser.objects.filter(email=email).exists():
user = auth.authenticate(email=email,password=password)
if user is not None:
auth.login(request,user)
messages.success(request,'Successfully Loggedin')
return redirect('/')
else:
messages.warning(request,'Password does not match')
return redirect('login')
else:
messages.error(request,'No Account registered with this mail')
return redirect('login')
except Exception as problem:
messages.error(request,problem)
return redirect('login')
return render(request,'login.html')
В рамках моего проекта я хочу иметь в своей базе данных два разных типа пользовательских таблиц, один для обычного пользователя, другой для администратора. Поэтому при создании пользовательской модели django я не добавил эту строку AUTH_USER_MODEL = 'accounts.User' в свой файл settings.py. Поэтому, когда я пытаюсь войти в систему или пройти аутентификацию с использованием этой пользовательской модели, она дает мне пароль, который не соответствует ошибке. Как я могу аутентифицировать его, не меняя модель django Auth. и пока я пытаюсь сделать этот пароль = пароль.set_password, это дает мне ошибку
'Str type object has no method set_password' , how can I log in or authenticate?```