I am new to django and have a question about models and the constraints the fields are supposed to enforce in the database (I am using Mongo). I built the following model for the user class, and want to make id the primary key, and email and password required. After making migrations and migrating to the mongo collection, I am able to make post requests access that data in the views, and then make and save a new user with those invalid emails. My understanding of model fields is that they should enforce certain constraints in the database. For example, models.EmailField should automatically check that the email being passed into is valid. Maybe I am incorrect in this or am missing something.
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
'''
Create and save a user with the given email, and password.
'''
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must have is_staff=True.'
)
if extra_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must have is_superuser=True.'
)
return self._create_user(email, password, **extra_fields)
class Meta:
managed = False
class User(AbstractBaseUser, PermissionsMixin):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(
unique=True,
max_length=255,
blank=False,
)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_(
'Designates whether the user can log into '
'this admin site.'
),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be '
'treated as active. Unselect this instead '
'of deleting accounts.'
),
)
date_joined = models.DateTimeField(
_('date joined'),
default=timezone.now,
)
# Add additional fields here if needed
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta:
db_table = 'user_credentials'