I have defined a custom user model using AbstractBaseUser class. Below is the implementation for your reference.
#models.py
class UserManager(BaseUserManager):
def create_user(self, email, firstname, lastname, contact, password):
if not email:
raise ValueError('You must provide an email address')
if not contact:
raise ValueError('You must provide a contact number')
email = self.normalize_email(email)
user = self.model(email=email, firstname=firstname, lastname=lastname, contact=contact)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, firstname, lastname, contact, password):
user = self.create_user(email, firstname, lastname, contact, password)
user.is_admin = True
user.save(using=self._db)
return user
class Users(AbstractBaseUser):
id = models.AutoField(primary_key=True)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
contact = models.CharField(max_length=10, unique=True)
email = models.EmailField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
is_staff = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['firstname', 'lastname', 'contact']
objects = UserManager()
def save(self, *args, **kwargs):
if not self.firstname or not self.lastname or not self.contact or not self.email or not self.password:
raise ValueError('All required fields must be provided')
super().save(*args, **kwargs)
def __str__(self):
return str(self.id) + '. ' + self.firstname + ' ' + self.lastname
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
class Meta:
db_table = 'users'
verbose_name_plural = 'Users'
Everything works well apart from setting password for a new user or updating same for an existing user in Django’s native Admin page. While setting password, it sets passwords in a plain text rather than hashing it.
Here’s my admin.py code.
#admin.py
from django.contrib import admin
from .models import *
admin.site.site_header = 'ROI Administration'
admin.site.site_title = 'ROI | Admin Panel'
admin.site.index_title = 'ROI Databases'
class UsersAdmin(admin.ModelAdmin):
ordering = ['id']
readonly_fields = ['id', 'created_at', 'last_login']
fieldsets = [
(None, {'fields': ['id', 'firstname', 'lastname', 'email', 'contact', 'last_login', 'created_at', 'is_staff', 'is_admin', 'password']}),
]
admin.site.register(Users, UsersAdmin)
Refer below the screenshot.
How do I resolve this?