The User model in Django helps manage who can use your website. It stores information like usernames and passwords so people can log in safely.
0
0
User model overview in Django
Introduction
When you want people to create accounts on your website.
When you need to check who is logged in to show personalized content.
When you want to control access to certain parts of your site.
When you want to store user details like email or name.
When you want to let users reset their passwords.
Syntax
Django
from django.contrib.auth.models import User # Create a new user user = User.objects.create_user(username='john', password='mypassword') # Access user fields print(user.username) print(user.email)
The User model is built into Django and ready to use.
You can create users, check their info, and manage passwords easily.
Examples
This creates a user with a username, email, and password.
Django
from django.contrib.auth.models import User # Create a user with email user = User.objects.create_user(username='anna', email='anna@example.com', password='secret123')
This gets a user by username and checks if their account is active.
Django
user = User.objects.get(username='john') print(user.is_active)
This changes the user's password safely.
Django
user.set_password('newpassword')
user.save()Sample Program
This example creates a user named Maria and prints her username, email, and if her account is active.
Django
from django.contrib.auth.models import User # Create a new user user = User.objects.create_user(username='maria', email='maria@example.com', password='pass1234') # Print user info print(f'Username: {user.username}') print(f'Email: {user.email}') print(f'Is active: {user.is_active}')
OutputSuccess
Important Notes
The default User model has fields like username, email, password, first_name, last_name, and is_active.
You can extend or replace the User model if you need more custom fields.
Always use Django's methods to set passwords to keep them secure.
Summary
The User model stores and manages user accounts in Django.
It helps with login, logout, and user info management.
You can create, update, and check users easily using Django's built-in tools.