Welcome to our comprehensive guide on creating a Custom User Model in Django! By the end of this tutorial, you'll understand how to customize the default user model to better suit your project's needs. π Note: This guide is suitable for both beginners and intermediates.
Django comes with a built-in user model AuthUser (derived from AbstractBaseUser and PermissionsMixin) which handles authentication and authorization. However, it may not always fit your application's requirements.
To create a custom user model, we'll follow these steps:
Let's call our custom user model MyUser.
python manage.py startapp custom_userscustom_users/models.py, create the MyUser class:from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class MyUserManager(BaseUserManager):
pass
class MyUser(AbstractBaseUser):
email = models.EmailField(verbose_name='email', max_length=255, unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['is_staff']# custom_users/models.py
from django.contrib.auth import get_user_model
class CustomUser(get_user_model()):
passsettings.py of your project, update AUTH_USER_MODEL:AUTH_USER_MODEL = 'custom_users.CustomUser'# custom_users/views.py
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from django.contrib.auth.forms import AuthenticationForm
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
user = form.get_user()
login(request, user)
next_url = request.GET.get('next')
if next_url:
return redirect(next_url)
else:
return redirect('home')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})What is the name of the custom user model we created in this tutorial?
You can add custom fields to your user model, such as first_name, last_name, age, etc. Just create a new field and add it to the MyUser class.
Django allows you to override user model methods like get_full_name(), get_short_name(), and more to better fit your application's needs.
Now that you've learned how to create a custom user model in Django, you're one step closer to building a robust web application! Happy coding! π‘ Pro Tip: Don't forget to test your custom user model thoroughly to ensure everything works as expected.