Create Your Custom User Model In Your Django Project
When you start a new project, one of the best things to do at the beginning is to create your custom user model
- Firstly: Create a new app for users.
$ python manage.py startapp users
- Add it to the installed app in the settings.py file.
INSTALLED_APPS = [
...
# Project Apps
'users.apps.UsersConfig',
]
- in the models.py create your custom model, we will use AbstractUser from django and then we can add new fields to our user model.
for example we will add an image.
# models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
image = models.ImageField('Image', upload_to='user/images',
null=True, blank=True)
class Meta:
verbose_name = 'User'
verbose_name_plural = 'Users'
def __str__(self):
return self.username
- In the settings.py add the Custom user settings
to inform Django to use our custom model for user instead of the default one.
AUTH_USER_MODEL = 'users.CustomUser'
- Register the model in the Django admin
we will use UserAdmin class and customize it as we need.
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import get_user_model
User = get_user_model()
@admin.register(User)
class CustomUserAdmin(UserAdmin):
model = User
list_display = ['__str__', 'email', 'username',
'is_staff', 'is_superuser', ]
list_filter = ['is_staff', 'is_superuser']
fieldsets = (
('Login info', {'fields': ('username', 'password')}),
('Personal info', {'fields': ('first_name', 'last_name', 'image')}),
('Contact info', {'fields': ('email', )}),
('Permissions', {'fields': ('is_active', 'groups',
'user_permissions')}),
)
add_fieldsets = (
(None, {
'classes': ('wide', ),
'fields': ('email', 'username', 'image',
'password1', 'password2')}
),
)
search_fields = ('email', 'username')
ordering = ('email', )
- Then run the migrations.
$ python manage.py makemigrations
$ python manage.py migrate
- Create a super user to test with.
$ python manage.py createsuperuser
And that's it! You got your own custom user model!
Stay tuned for the next article
We will fix an issue in Django, take a note of this article because we will continue upon it.
Feel free to reach out if you have any questions.
Join to discord Server Here - Django Learn Together.
Views: 705