<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fahim Ahmed Irfan on Medium]]></title>
        <description><![CDATA[Stories by Fahim Ahmed Irfan on Medium]]></description>
        <link>https://medium.com/@fahimirfan70?source=rss-9bfcd6f3ee31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MVx-WMOTtytD8vLd</url>
            <title>Stories by Fahim Ahmed Irfan on Medium</title>
            <link>https://medium.com/@fahimirfan70?source=rss-9bfcd6f3ee31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:01:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fahimirfan70/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[User creation using Django AbstractBaseUser and Login using JWT web authentication]]></title>
            <link>https://fahimirfan70.medium.com/user-creation-using-django-abstractbaseuser-and-login-using-jwt-web-authentication-5d9fbfdd14ed?source=rss-9bfcd6f3ee31------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d9fbfdd14ed</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fahim Ahmed Irfan]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 20:23:41 GMT</pubDate>
            <atom:updated>2021-06-03T20:23:41.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*kR89JbQQK9aAkNVyxE63pg.png" /></figure><p>In this article, I will try to cover Django user creation, defining a custom user mode extending <strong>AbstractBaseUser</strong> class and <strong>JWT web authentication</strong> for user Login.</p><p>I will use <strong>Django Rest Framework</strong> for making sign up API and Login API will be provided by <strong>JWT web authentication</strong>.</p><p>First, we need to create a project using django-admin startproject command:</p><pre>django-admin startproject custom_auth</pre><p>Then we need to activate virtual environment and install the necessary packages for completing this project. We will install all the packages using <strong>pip. </strong>Run these commands one by one:</p><pre>pip install django<br>pip install postgres<br>pip install djangorestframework<br>pip install djangorestframework-simplejwt</pre><p>Now we need to modify our project settings.py file to configure the project.</p><p>Configure database section:</p><pre>DATABASES = {<br>    &#39;default&#39;: {<br>         &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>         &#39;NAME&#39;: &#39;&#39;,<br>         &#39;USER&#39;: &#39;&#39;,<br>         &#39;PASSWORD&#39;: &#39;&#39;,<br>         &#39;HOST&#39;: &#39;localhost&#39;,<br>         &#39;PORT&#39;: &#39;5432&#39;,<br>   }<br>}</pre><p><em>Please provide the preferred name, user, and password.</em></p><p>Modify installed apps:</p><pre>INSTALLED_APPS = [<br>.....<br>.....<br>&#39;rest_framework&#39;,<br>&#39;rest_framework_simplejwt&#39;,<br>.....<br>.....<br>]</pre><p>Add rest framework configs:</p><pre># Rest framework<br>REST_FRAMEWORK = {<br>&#39;DEFAULT_PERMISSION_CLASSES&#39;: (&#39;rest_framework.permissions.IsAuthenticated&#39;,),</pre><pre>&#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (&#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,)<br>}</pre><p>Now need to migrate database:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>If these two commands run without any error, this means the project is ready.</p><p>After that, we need to go to the project directory, in this case, the directory is custom_auth, here we will run startapp command for creating our apps.</p><p>I will create a core app. Normally I keep all the model classes in one models.py and that is in the core app.</p><p>Create app:</p><pre>python manage.py startapp core</pre><p>Now register this app to settings.py INSTALLED_APP section</p><p>Now we need to write custom user model class in models.py. First, we need to create a manager class extending from <strong>BaseUserManager</strong>. This class mainly manages user creation for the different privileged users.</p><pre>class UserProfileManager(BaseUserManager):<br>&quot;&quot;&quot;<br>Defines user creation fields and manages to save user<br>&quot;&quot;&quot;<br>def create_user(self, email, username, password=None):<br>     if not email:<br>          raise ValueError(&#39;Users must have an email address&#39;)<br>     user = self.model(email=self.normalize_email(email),<br>            username=username,<br>     )<br>     user.set_password(password)<br>     user.save(using=self._db)<br>     <br>     return user</pre><pre>def create_staffuser(self, email,username, password=None):<br>     user = self.create_user(email,<br>             password=password,<br>             username=username<br>     )</pre><pre>     user.is_staff = True<br>     user.save(using=self._db)<br>     <br>     return user</pre><pre>def create_superuser(self, email, username, password=None):<br>     user = self.create_user(email,<br>            password=password,<br>            username=username<br>     )<br>     user.is_staff = True<br>     user.is_admin = True<br>     user.save(using=self._db)<br>     <br>     return user</pre><p>Now we need to create custom user model extending <strong>AbstractBaseUser. </strong>This class saves user information to database.</p><pre>class UserProfile(AbstractBaseUser):<br>&quot;&quot;&quot;<br>Creates a customized database table for user using customized user manager<br>&quot;&quot;&quot;</pre><pre>     email = models.EmailField(verbose_name=&#39;email address&#39;,<br>             max_length=255,unique=True,<br>             )<br>     username = models.CharField(_(&#39;username&#39;),<br>              max_length=150,<br>              unique=True,<br>              error_messages={<br>   &#39;unique&#39;: _(&quot;A user with that username already      exists.&quot;),<br>       },<br>    )<br>     is_active = models.BooleanField(default=True)<br>     is_staff = models.BooleanField(default=False)<br>     is_admin = models.BooleanField(default=False)<br>     <br>     USERNAME_FIELD = &#39;username&#39;<br>     REQUIRED_FIELDS = [&#39;email&#39;,]</pre><pre>     objects = UserProfileManager()</pre><pre>def get_full_name(self):<br>     return self.email</pre><pre>def get_short_name(self):<br>     return self.email</pre><pre>def __str__(self):<br>     return self.email</pre><pre>def has_perm(self, perm, obj=None):<br>     return True</pre><pre>def has_module_perms(self, app_label):<br>     return True</pre><p>After that, we need to tell django that we are using custom user model. For this to settings.py:</p><pre>AUTH_USER_MODEL = &#39;core.UserProfile&#39;</pre><p>We need to register this model to core app’s admin.py also. In admin.py:</p><pre>from django.contrib.auth import get_user_model</pre><pre>UserProfile = get_user_model()<br>admin.site.register(UserProfile)</pre><p>Now migrate these models. Once migration is done, we will create superuser:</p><pre>python manage.py createsuperuser</pre><p>After that, we will run our local server:</p><pre>python manage.py runserver</pre><p>Now, we will visit Django administration to see our registered custom user model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*BzA090MyoZzEdHYd_Dt96A.jpeg" /><figcaption>User Profiles registered in Django admin</figcaption></figure><p>So, if we can reach here successfully, we can say we have done our half works. Now we need to create sign up API and login API. First, we need to setup rest framework in settings.py (if not we set it up earlier):</p><pre># Rest framework</pre><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PERMISSION_CLASSES&#39;:     (&#39;rest_framework.permissions.IsAuthenticated&#39;,),<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (&#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,)<br>}</pre><p>We need to create an app called authentication. Here, we write our APIs for sign up and login. We need to set up our authentication app’s url and need to register the urls to project’s urls.py</p><pre>urlpatterns = [<br>      path(&#39;admin/&#39;, admin.site.urls),<br>      path(&#39;auth/&#39;, include(&#39;authentication.urls&#39;,<br>              namespace=&#39;authentication&#39;))<br>]</pre><p>First, we need to define our sign up fields in ModelSerializer. Create a serializers.py in authentication app.</p><pre>from core.models import UserProfile<br>from rest_framework import fields, serializers<br>from django.contrib.auth.hashers import make_password<br>from django.contrib.auth.password_validation import validate_password</pre><pre>class SignupSerializer(serializers.ModelSerializer):<br>&quot;&quot;&quot;<br>Serializer for creating new user using signup form<br>&quot;&quot;&quot;<br>      class Meta:<br>          model = UserProfile<br>          fields = [&#39;id&#39;, &#39;username&#39;, &#39;email&#39;, &#39;password&#39;]<br>          extra_kwargs = {&#39;password&#39;: {&#39;write_only&#39;: True}} <br>      def create(self, validated_data): <br>          if validate_password(validated_data[&#39;password&#39;]) == None:<br>               password = make_password(validated_data[&#39;password&#39;])                          </pre><pre>               user = UserProfile.objects.create(<br>                      username=validated_data[&#39;username&#39;],<br>                      email=validated_data[&#39;email&#39;],<br>                      password=password<br>          )</pre><pre>return user</pre><p>In this serializer model, we validate our sign up data. If everything is fine, the model serializer will make the data ready to be saved.</p><p>Now, we will create our sign up APIView in views.py:</p><pre>from core.models import UserProfile<br>from rest_framework.exceptions import ValidationError<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br>from rest_framework.permissions import IsAuthenticated<br>from . serializers import SignupSerializer</pre><pre># Create your views here.</pre><pre>class SignupAPIView(APIView):<br>&quot;&quot;&quot;<br>API view for sign up API<br>&quot;&quot;&quot;</pre><pre>     permission_classes = []</pre><pre>     def post(self, request):<br>         password = request.POST.get(&#39;password&#39;, None)<br>         confirm_password = request.POST.get(&#39;confirm_password&#39;, None)<br>         if password == confirm_password: <br>              serializer = SignupSerializer(data=request.data)<br>              serializer.is_valid(raise_exception=True)<br>              serializer.save()<br>              data = serializer.data<br>              response = status.HTTP_201_CREATED<br>         else:<br>              data = &#39;&#39;<br>              raise ValidationError(<br>        {&#39;password_mismatch&#39;: &#39;Password fields didn not match.&#39;})</pre><pre>     return Response(data, status=response)</pre><p>This view will post sign up data to database. Now we need to set API endpoint in urls.py:</p><pre>from django.urls import path<br>from  .views import SignupAPIView</pre><pre>app_name = &#39;authentication&#39;</pre><pre>urlpatterns = [<br>     path(&#39;signup/&#39;, SignupAPIView.as_view(), name=&#39;signup&#39;)<br>]</pre><p>Now we need to test the API. For testing purposes, we will postman. It is a very useful tool for testing API. In postman it will look like the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*tyhUiE-NaV8NQNg88HZY-w.png" /><figcaption>Sign up API in postman</figcaption></figure><p>Make sure the keys are similar to serializers fields. If not, then it may cause some error.</p><p>Now the final part. In this part we need to create login API. For that, we need setup JWT authentication in settings.py:</p><pre># JWT</pre><pre>SIMPLE_JWT = {<br>     &#39;ACCESS_TOKEN_LIFETIME&#39;: datetime.timedelta(minutes=30),</pre><pre>     &#39;REFRESH_TOKEN_LIFETIME&#39;: datetime.timedelta(days=1),<br>}</pre><p>Access token authenticates a user and refresh token is used for generating access token once access token’s lifetime is over. Now we need to setup the endpoints for generating this tokens. In authentication app’s url.py:</p><pre>from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView</pre><pre><br># JWT</pre><pre>urlpatterns = [<br>path(&#39;token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),</pre><pre>path(&#39;token/refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),</pre><pre>path(&#39;token/verify/&#39;, TokenVerifyView.as_view(), name=&#39;token_verify&#39;),<br>]</pre><p><strong>TokenObtainPairView </strong>will create access token and refresh and<strong> </strong>TokenRefreshView will create access token from refresh token.</p><p>Now we need to test this APIs in postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*E1iYTYoyVIb-dwVDlHy5Vg.png" /><figcaption>Generates access and refresh token using token/ API</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*7V5aGFen7_z_SV8AOXZOjQ.jpeg" /><figcaption>Generates access token using /token/refresh/ API</figcaption></figure><p>So after all these hard works, finally we are able to use custom user model to create new user and JWT web authentication to authenticate the users.</p><p>Find the whole project in github: <a href="https://github.com/Irfan995/django-custom-auth">https://github.com/Irfan995/django-custom-auth</a></p><p>For more details, must see the official documentation:</p><ol><li><a href="https://docs.djangoproject.com/en/3.2/topics/auth/customizing/">https://docs.djangoproject.com/en/3.2/topics/auth/customizing/</a></li><li><a href="https://www.django-rest-framework.org/">https://www.django-rest-framework.org/</a></li><li><a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">https://django-rest-framework-simplejwt.readthedocs.io/en/latest/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d9fbfdd14ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>