Creating and Managing Users in Django
Django provides a robust authentication system that includes tools for creating and managing users. This article explains how to create users, manage their data, and handle authentication in Django.
1. Using the Default User Model
Django's default User
model is located in django.contrib.auth.models
. It includes fields like username, email, password, and more. You can use it to create and manage users.
Creating a User
# Create a user using the Django shell
from django.contrib.auth.models import User
# Create a new user
user = User.objects.create_user(username='john', email='john@example.com', password='mypassword')
user.save()
The create_user()
method hashes the password automatically.
Superuser Creation
You can create a superuser (admin) using the createsuperuser
management command:
# Run this command in the terminal
python manage.py createsuperuser
Follow the prompts to set up the superuser's credentials.
2. Registering Users via Forms
To allow user registration, you can create a registration form using the default user model:
# forms.py
from django import forms
from django.contrib.auth.models import User
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
def clean_confirm_password(self):
password = self.cleaned_data.get('password')
confirm_password = self.cleaned_data.get('confirm_password')
if password != confirm_password:
raise forms.ValidationError("Passwords do not match.")
return confirm_password
Handling Registration in a View
# views.py
from django.shortcuts import render, redirect
from .forms import UserRegistrationForm
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(form.cleaned_data['password']) # Hash the password
user.save()
return redirect('login')
else:
form = UserRegistrationForm()
return render(request, 'register.html', {'form': form})
3. Authenticating and Logging In Users
Use Django's built-in authentication methods to log users in and out:
# views.py
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
def login_view(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
return render(request, 'login.html', {'error': 'Invalid credentials'})
return render(request, 'login.html')
def logout_view(request):
logout(request)
return redirect('login')
4. Managing Users
Once users are created, you can manage them using the Django admin interface or programmatically:
# Updating user information
user = User.objects.get(username='john')
user.email = 'john.new@example.com'
user.save()
# Deleting a user
user.delete()
5. Customizing the User Model
If the default user model does not meet your needs, you can create a custom user model by extending AbstractUser
:
# models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
phone_number = models.CharField(max_length=15, blank=True)
# settings.py
AUTH_USER_MODEL = 'yourapp.CustomUser'
This allows you to add custom fields like phone_number
.
6. Using Django's Built-in Views
Django provides ready-to-use views for user management:
# urls.py
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
]
7. Conclusion
In Django, managing users is straightforward with the built-in authentication framework. You can create users using the default model, customize it, and use built-in views for handling authentication. These tools provide flexibility and security for user management in your applications.