Модель User и authenticate()
Проверяйте учётные данные с помощью встроенного пользователя
«Модель User и authenticate()» — бесплатный урок Django Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Django Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Django Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
You Already Have Users
Django ships a full User model out of the box, so you never write account tables by hand. It stores usernames, hashed passwords, and more. 👤
Where the User Lives
The model sits in django.contrib.auth, an app that is enabled in fresh projects. Import it and the whole auth toolkit comes along.
from django.contrib.auth.models import UserKey User Fields
Each user has a username, plus email, first_name, and last_name. These are the everyday fields you read and display in your app.
Passwords Are Never Plain
Django stores a salted hash of every password, never the raw text. Even you, the developer, cannot read a user's actual password. 🔒
Create a User Safely
Use create_user so the password gets hashed for you. Setting the password by hand would store it in the clear.
User.objects.create_user(username="ada", password="secret123")Meet authenticate()
The authenticate() function checks a username and password against the database for you. It is the heart of every login flow.
from django.contrib.auth import authenticateHow authenticate() Works
Pass it the credentials and it returns the matching user object when they are correct. No hashing or lookups for you to write.
user = authenticate(username="ada", password="secret123")When Credentials Fail
If the username or password is wrong, authenticate() returns None. Always check for that before treating the user as logged in.
if user is None:
print("Invalid credentials")Active Users Only
The is_active flag lets you disable accounts. By default authenticate() refuses to return inactive users, blocking banned logins.
Staff and Superusers
Two extra flags matter: is_staff grants admin-site access, and is_superuser grants every permission. Most users have neither.
Authenticate Is Not Login
Remember: authenticate() only verifies identity. It does not start a session, so the user is not yet logged in after this call.
Quick Check
What does authenticate() return when the password is wrong?
Recap: Users and Identity
You met Django's built-in User model and used authenticate() to verify credentials. Passwords stay hashed, and a failed check gives None. ✅
Часто задаваемые вопросы
Урок «Модель User и authenticate()» бесплатный?
Да — полный текст урока «Модель User и authenticate()» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Django Academy, подпишись на CoddyKit PRO. Курс Django Academy содержит 4 уроков всего.
Чему я научусь в уроке «Модель User и authenticate()»?
Проверяйте учётные данные с помощью встроенного пользователя Ты практикуешь Django Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Django Academy?
Предыдущий опыт не требуется. Django Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Модель User и authenticate()»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Django Academy?
Да. Каждый урок Django Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Модель User и authenticate()
- login, logout и представления аутентификации
- Регистрация с UserCreationForm
- login_required и защита представлений