Coverage for src/accounts/models/user_credential.py: 94%
17 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-08-04 12:59 +0300
« prev ^ index » next coverage.py v7.9.2, created at 2025-08-04 12:59 +0300
1"""
2This module defines the custom user model for the e-commerce application.
3Instead of using Django's default User model, we create a custom one that
4extends AbstractBaseUser and PermissionsMixin.
6The custom user model allows us to:
7- Use email as the primary identifier instead of username
8- Add custom fields like agreed_to_emails
9- Implement custom validation and business logic
10"""
12from django.contrib.auth.models import PermissionsMixin
13from django.contrib.auth.base_user import AbstractBaseUser
14from django.db import models
16from src.accounts.managers import UserCredentialManager
17from src.accounts.validators.models import UsernameValidator
18from src.accounts.constants import UserFieldLengths, UserErrorMessages
21class UserCredential(AbstractBaseUser, PermissionsMixin):
23 # Email field as the primary identifier
24 email = models.EmailField(
25 unique=True,
26 error_messages={
27 'unique': UserErrorMessages.EMAIL_UNIQUE, # Custom error message
28 },
29 )
31 # Username field for display purposes
32 username = models.CharField(
33 max_length=UserFieldLengths.USERNAME_MAX, # Defined in constants
34 unique=True,
35 validators=[
36 UsernameValidator(), # Custom validator for username format
37 ],
38 error_messages={
39 'unique': UserErrorMessages.USERNAME_UNIQUE, # Custom error message
40 },
41 )
43 # This tracks whether the user has agreed to receive marketing emails
44 agreed_to_emails = models.BooleanField(
45 default=False,
46 )
48 is_active = models.BooleanField(
49 default=True,
50 )
52 is_staff = models.BooleanField(
53 default=False,
54 )
56 # Custom manager for user creation and queries
57 objects = UserCredentialManager()
59 # USERNAME_FIELD tells Django which field to use for authentication
60 USERNAME_FIELD = 'email'
62 # REQUIRED_FIELDS specifies which fields are required when creating an user
63 REQUIRED_FIELDS = ['username']
65 def __str__(self):
66 return self.email