StaffCoder
Django
DjangoDjango 5.2Python 3.13
18 modules · 72 challengesSign up
Module 9 · Authentication & Authorization

Email Login Custom User

mediumDjango AuthenticationModels100%2 of 2 solved

Problem statement

In this Django project, implement the user model the product actually signs people up with: an email address, not a username. Replace the placeholder User in app/models.py with one built on AbstractBaseUser and PermissionsMixin, and write the manager that creates users and superusers. AUTH_USER_MODEL already points at this class, so every session, every request.user and every authenticate() call goes through what you write here.

Requirements

Implement:

  • the User model in app/models.py
  • the BaseUserManager subclass that User.objects uses, in app/models.py

The following files are already implemented and provided: app/views.py, app/urls.py, project/settings.py and both templates. AUTH_USER_MODEL = "app.User" has been in project/settings.py since the project's first migration, and the setting is read-only, so the class keeps the name User. LOGIN_URL, LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL are set there too. The accounts/ routes are Django's own LoginView and LogoutView, and neither names a field: the login form asks the user model which field identifies a person and labels its box from that. app/migrations/ holds no migration - under manage.py test the tables are built straight from the models, and the run command calls makemigrations app before migrate.

What is in app/models.py now is a placeholder: a User with a username field, USERNAME_FIELD = "username", an optional email and the plain default manager. It imports and its tables build, so the project starts.

1. The User model

  • Built on AbstractBaseUser and PermissionsMixin, with a unique email, no username field at all, and USERNAME_FIELD = "email". Do not keep the placeholder's username "just in case".
  • is_staff has to be a real field, since the manager sets it. is_active can stay the class attribute AbstractBaseUser already gives you, or be a field defaulting to True.
  • REQUIRED_FIELDS stays the empty list. It names the extra fields createsuperuser prompts for besides USERNAME_FIELD, so putting email in it names the identity field twice, fails the auth.E002 system check and stops createsuperuser from running at all.

2. The manager

  • A BaseUserManager subclass attached as objects. createsuperuser calls create_superuser, and anything that signs somebody up calls create_user.
  • create_user(email, password=None, **extra_fields) stores the normalized email, hashes the password, saves the user and returns it. It sets no elevated flags, so a new user comes out with is_active true, is_staff false and is_superuser false.
  • create_superuser(email, password=None, **extra_fields) does the same with is_staff and is_superuser defaulting to True, so a caller who passes neither gets an administrator. The usual shape is to hand the work to create_user once the flags are set, which is also how it inherits the rule below.
  • Normalize with BaseUserManager.normalize_email, which lowercases the domain and leaves the local part exactly as typed: Ada.Lovelace@Example.COM is stored as Ada.Lovelace@example.com. Domains are case-insensitive; mailbox names are not.
  • Build the instance with self.model(...) rather than naming the class, and write with save(using=self._db), so a subclass or a second database still works.

3. A user with no email is refused

  • create_user raises ValueError when the email is empty or missing, and writes nothing. The message is exactly:
Users must have an email address
  • A real address is of course still accepted by the same call.

Notes

  • The field USERNAME_FIELD names must be unique. If it is not, Django's auth.E003 system check fails and the project refuses to start, so nothing runs at all.
  • Hash through set_password or make_password, never by assigning the raw value: an assigned .password stores the secret as typed and no later check_password can match it.
  • AbstractBaseUser brings the password machinery and nothing else (a password column, set_password, check_password, last_login, and is_active = True as a class attribute); PermissionsMixin brings is_superuser, groups, user_permissions and the has_perm family. Neither brings a username, an email or a name.
  • Do not touch AUTH_USER_MODEL, do not write an authentication backend (Django's own backend reads USERNAME_FIELD for you), and do not write a migration by hand.

More in Authentication & Authorization

See the module
Session Access FlowThe site has member pages but no way to sign in, and the protected views are protected by nothing. Wire Django's built-in LoginView and LogoutView with your own login template, gate the member views with login_required, and send a visitor back to the page they originally asked for.100%2 of 2 solvedmediumPermission Gated PublishingPublishing and unpublishing are gated on being signed in and nothing more, so every author can change the state of anyone's article. Gate both actions on the model permission app.publish_article, hide the controls from a visitor who does not hold it, and let the editors group grant it.100%2 of 2 solvedmediumMembers Area Access MatrixThe members area has a public page, member pages, permission-gated actions and a staff-only section, and today every one of them is reachable by everyone. Enforce the whole access matrix across the view and template layers, with a login redirect for anonymous visitors and a 403 for signed-in visitors who are not allowed.100%2 of 2 solvedmedium

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.