Hello, in my project, I want to change the minimum length of the username field on the built in user model.
To do this, should I inherit from the AbstractUser, and override the username property to have the minimum length I need, or should I inherit from the AbstractBaseUser class? Which method is best to accomplish this? Thanks.
Hi
Model fields don’t have a minimum length. This is a form-only property. I think you should be able to get away with changing just form fields to add this minimum length through a MinLengthValidator
.
Thanks,
Adam
1 Like
Hi. So your saying you don’t have to specify any min/max length validators on the model fields, but the forms ?
What about if someone bypasses the form, and tries to insert data straight into the database, and they are able to specify a user with username of length 1 for example.
Does Django have anything in place to cover this possibility?
You can add a CheckConstraint
for the field in that case, for example, here’s a Book with a title whose length is at least 1 character:
from django.db import models
from django.db.models.functions import Length
# Register __length transform as per Length documentation
models.CharField.register_lookup(Length)
class Book(models.Model):
title = models.CharField(max_length=200)
class Meta:
constraints = [
models.CheckConstraint(
check=models.Q(title__length__gte=1),
name="%(app_label)s_%(class)s_title_length",
)
]
2 Likes
Great, thank you, this helps a lot.
Hi Adam,
conceptually, what’s the difference between CheckConstraint
and a Validator
? What’s the use case for each?
Sorry if this is off topic.
CheckConstraint
- in the database
Validator
- in forms
1 Like
Quick and effective.
Thanks!