Django allows for the extension of the default user model, enabling the customization of user-related data. This guide outlines the steps to create a custom user model.
-
Preview data in terminal/console:
python manage.py dumpdata
- This will show all data in the database.
- To filter, add the app name:
python manage.py dumpdata app_name
-
Create backup, write to file in project root:
python manage.py dumpdata > backup.json
-
Create a new app:
python manage.py startapp user
-
Register the new app in
settings.py
. -
Register UserModel in
settings.py
(at the bottom):AUTH_USER_MODEL = "user.User" # nameOfApp.nameOfModel
-
Create the user model in
models.py
:from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass
-
Remove old user imports from models, replace with new user model:
from django.contrib.auth import get_user_model User = get_user_model()
-
Delete old SQLite database.
-
Delete old migrations.
-
Make migrations and migrate. If
user.user
table shows up in IDE database, all is good. -
(Optional) Change
auth.user
touser.user
inbackup.json
. (This is only necessary if you want to import the old data.) -
Import database backup:
python manage.py loaddata backup.json
- Register UserTable in admin:
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin User = get_user_model() admin.site.register(User, UserAdmin)
-
Overwrite
AbstractUser
with email as login in User Model:from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # Overwrite required fields
-
Fix Admin Registration:
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User class CustomUserAdmin(UserAdmin): readonly_fields = ('date_joined',) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username', 'password1', 'password2')} ), ) fieldsets = ( (None, {'fields': ('email', 'username', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ('Groups', {'fields': ('groups',)}), ) admin.site.register(User, CustomUserAdmin)