Skip to content
Related Articles

Related Articles

Improve Article

Creating custom user model using AbstractUser in django_Restframework

  • Difficulty Level : Expert
  • Last Updated : 23 Oct, 2020

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

Steps to create Custom User Model

  • Create and navigate into a dedicated directory called users for our code

    $ cd ~/Desktop$ mkdir code && cd code
  • Install Django
    $ pipenv install django
  • Make a new Django project called login

    $ django-admin startproject login
  • Make a new app API and install rest framework
    $ python startapp api
    $ pipenv install rest_framework
  • Now we need to configure our settings. py as follow

      # Add these lines to to your installed apps section in settings. py
    AUTH_USER_MODEL ='api.urls'
  • After this we need to create a custom user model. For this change your fille. Here we are extending AbstractUser and changing authentication credentials to Email and we are also adding some extra fields in our custom user

    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(
  • After this we need to save these changes to the admin pannel as well. Add this code to the

    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', ), UserAdmin)
  • Now create a file in your app. Add following code to your

    from rest_framework import serializers
    from api.models import  User
    class UserSerializer(serializers.ModelSerializer):
      class Meta:
          model = User
          fields = "__all__"
  • We are almost done. Now create api/  file inside you app and add following lines

    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/ of your project

    from django.contrib import admin
    from django.urls import path
    urlpatterns = [
      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 makemigrations users
    $ python migrate
  • Now create a superuser
    $ python createsuperuser
    Email address:
    Password (again):
    Superuser created successfully.
  • Now run server with.
    $ python runserver

     Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

    To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

    My Personal Notes arrow_drop_up
  • Recommended Articles
    Page :