🎓 A1Learner
🔍
0 of 50 lessons completed

The Django User Model

The User model holds the readers of a site. Each user has a name and a password.

Make a user

This line makes a user named sana. The password is scrambled as it is stored.

user = User.objects.create_user("sana", password="secret123")

Count the users

The user is made first. The count shows one user, and the name reads back.

User.objects.create_user("sana", password="secret123")
print(User.objects.count())
print(User.objects.get(username="sana").username)

Check the password

check_password tests a password against the stored one. The right password gives True.

user = User.objects.create_user("sana", password="secret123")
print(user.check_password("secret123"))

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=[
        "django.contrib.contenttypes",
        "django.contrib.auth",
    ],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()

from django.core.management import call_command
from django.contrib.auth.models import User

call_command("migrate", verbosity=0)

user = User.objects.create_user("sana", password="secret123")
print(User.objects.count())
print(user.username)
print(user.check_password("secret123"))
print(user.check_password("wrong"))

Key points

  • The User model comes from the auth app.
  • The auth app is the part of Django that handles users.
  • User.objects.create_user makes a new user.
  • A password is stored scrambled, never as plain text.
  • check_password tests a password against the stored one.
  • The User model is the list of readers for a site.

In this example, the setup lines configure Django. The program runs migrations first. The program makes a user named sana with a password. The prints show the user count of 1 and the user name. They show True for the right password and False for a wrong one.

Note

A user needs a name and a password to log in later.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does User.objects.create_user do?