Creating custom user model API extending AbstractUser in Django
Last Updated :
25 Oct, 2021
Every new Django project should use a custom user model. The official Django documentation says it is “highly recommended” but I’ll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front.
Why do u need a custom user model in Django?
When you start your project with a custom user model, stop to consider if this is the right choice for your project. Keeping all user related information in one model removes the need for additional or more complex database queries to retrieve related models. On the other hand, it may be more suitable to store app-specific user information in a model that has a relation with your custom user model. That allows each app to specify its own user data requirements without potentially conflicting or breaking assumptions by other apps. It also means that you would keep your user model as simple as possible, focused on authentication, and following the minimum requirements Django expects custom user models to meet.
So i think its clear why we need a custom user model in django, here in this article we are going to learn how to create custom user model and its api in django now, lets begin with the coding part .
Setup -
-
Create and navigate into a dedicated directory called users for our code
-
make a new Django project called login
-
make a new app users
-
start the local web server
Commands -
$ cd ~/Desktop
$ mkdir code && cd code
$ pipenv install django
$ pipenv shell
$ django-admin startproject login
$ python manage.py startapp api
$ pipenv install rest_framework
Now, add following code in settings.py,
Python3
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Add these lines to to your
# installed apps section in settings. py
'rest_framework',
'rest_framework.authtoken',
'api',
'rest_auth'
]
AUTH_USER_MODEL ='api.urls'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
After this we need to create a custom user model. For this change your models.py file as following. Here we are extending AbstractUser and changing authentication credentials to Email. And we are also adding some extra fields in our custom user
Python3
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from datetime import date
class User(AbstractUser):
username = models.CharField(max_length = 50, blank = True, null = True, unique = True)
email = models.EmailField(_('email address'), unique = True)
native_name = models.CharField(max_length = 5)
phone_no = models.CharField(max_length = 10)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
def __str__(self):
return "{}".format(self.email)
After this we need to save these changes to the admin panel as well. Add this code to the admin.py
Python3
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .models import User
class UserAdmin(BaseUserAdmin):
form = UserChangeForm
fieldsets = (
(None, {'fields': ('email', 'password', )}),
(_('Personal info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
(_('user_info'), {'fields': ('native_name', 'phone_no')}),
)
add_fieldsets = (
(None, {
'classes': ('wide', ),
'fields': ('email', 'password1', 'password2'),
}),
)
list_display = ['email', 'first_name', 'last_name', 'is_staff', 'native_name', 'phone_no']
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email', )
admin.site.register(User, UserAdmin)
Now create a serializers.py file in your app. Add following code to your serializers. py
Python3
rom rest_framework import serializers
from api.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
Now create api/urls.py file inside you app and add following lines
Python3
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('auth/', include('rest_auth.urls')),
]
Now add following code to the login/urls.py of your project
Python3
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path(" ", include("api.urls"))
]
We are all set with the custom user model. Now save these changes to you project and makemigrations through CLI
$ python manage.py makemigrations users
$ python manage.py migrate
Now create a superuser
$ python manage.py createsuperuser
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.
Now run server with.
$ python manage.py runserver
And go through the URL. You can check your custom user in the admin panel
Output -
Similar Reads
Creating custom user model using AbstractUser in django_Restframework
Every new Django project should use a custom user model. The official Django documentation says it is âhighly recommendedâ but Iâll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front. Why do u need a custom user model in Django? When you s
4 min read
How to create Abstract Model Class in Django?
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. W
2 min read
Python | Extending and customizing django-allauth
Django-allauth is a powerful Django package that simplifies user authentication, registration, account management, and integration with social platforms like Google, Facebook, etc. It builds on Djangoâs built-in authentication system, providing a full suite of ready-to-use views and forms.Prerequisi
4 min read
Built in & Custom Model Managers in Django
Django manager is a class that acts as an interface through which Django models interact with databases. Every model has at least one manager object. It has a lot of methods, attributes to ease working with databases. In fact, many beginner-level Django developers do not know that they use the Manag
6 min read
How to Add a Custom Field in ModelSerializer in Django
A key component of Django Rest Framework (DRF) is the Serializer, which converts complex data types like Django models into JSON, XML, or other content types. The ModelSerializer, a subclass of Serializer, automatically creates fields based on the modelâs fields, significantly reducing boilerplate c
4 min read
Customizing Phone Number Authentication in Django
We will implement phone number-based authentication in Django by creating a custom user model that uses phone numbers instead of usernames for login. Youâll learn how to build a custom user manager, update settings, and integrate the new user model with the Django admin panel to enhance security and
2 min read
How to Extend User Model in Django
Djangoâs built-in User model is useful, but it may not always meet your requirements. Fortunately, Django provides a way to extend the User model to add additional fields and methods. In this article, we'll walk through the process of extending the User model by creating a small web project that dis
3 min read
How to Get the Currently Logged In User's ID in Django?
Getting the ID of the currently logged-in user is a very common requirement when building user-centered web applications in Django. Through its built-in authentication system, Django allows easy access to the details of the user who is logged in at any time; this includes their unique ID. We can eas
4 min read
Automatic Creation Date for Django Model Form Objects
In many web applications, itâs often important to keep track of when an object was created and updated. This can be useful for auditing, sorting, or simply understanding the timeline of our data. Django provides a simple way to automatically manage these timestamps using the auto_now_add and auto_no
4 min read
Django Introduction | Set 2 (Creating a Project)
Note- This article is in continuation of Django introduction. Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Si
3 min read