{"id":119328,"date":"2024-11-26T09:31:55","date_gmt":"2024-11-26T09:31:55","guid":{"rendered":"\/tutorials\/?p=119328"},"modified":"2025-05-22T07:40:13","modified_gmt":"2025-05-22T07:40:13","slug":"django-user-model","status":"publish","type":"post","link":"\/tutorials\/django-user-model","title":{"rendered":"Django user model: What it is, how to use it and more"},"content":{"rendered":"<p><span style=\"margin: 0px;padding: 0px\">The Django&nbsp;<strong>User&nbsp;<\/strong>model provides a <\/span>solid foundation for managing users, securing content, and controlling access to your web applications. As you develop more dynamic and complex projects with Django, these models enable you to implement user authentication and authorization efficiently and securely.<\/p><p>In this article, we&rsquo;ll explain what the Django <strong>User<\/strong> model is, how to set it up, and how to customize it to suit your needs. We&rsquo;ll also discuss user permissions and authorization to provide strong application security.<\/p><p>\n\n\n\n\n\n\n<\/p><h2 class=\"wp-block-heading\" id=\"h-what-is-django-user-model\">What is Django User model?<\/h2><p>Django&rsquo;s built-in authentication system centers around the User model, which manages user accounts, permissions, and essential authentication tasks like login, logout, and password management. <\/p><p>This model comes ready to use, simplifying user management and security for your application.<\/p><p>Django provides authentication views and tools that cover most needs. If your project requires custom user registration or specific behaviors, you can extend the User model or add tailored functionality to fit your application&rsquo;s unique requirements.<\/p><h3 class=\"wp-block-heading\" id=\"h-overview-of-user-authentication-features\">Overview of user authentication features<\/h3><p>The default Django <strong>User<\/strong> model includes essential features for user authentication and management, such as fields for username, password, email, and permissions (like <strong>is_staff<\/strong> and <strong>is_superuser<\/strong> flags).<\/p><p>It provides built-in methods for password hashing and integrates with Django&rsquo;s authentication framework to handle login, logout, and access control. Combined with the permissions and session frameworks, it simplifies managing user sessions and roles securely.<\/p><h2 class=\"wp-block-heading\" id=\"h-how-to-use-the-default-django-user-model\">How to use the default Django User model?<\/h2><p>Choosing the default <strong>User<\/strong> model over a custom one can speed up development, as it offers ready-made features like authentication, permissions, and password management without requiring extra setup.<\/p><p>This makes it a great choice for projects with simple user requirements.<\/p><h3 class=\"wp-block-heading\" id=\"h-set-up-user-login-and-logout\">Set up user login and logout<\/h3><p><a href=\"\/tutorials\/building-django-views\">Django&rsquo;s built-in views<\/a> in <strong>django.contrib.auth.views<\/strong> make it easy to implement login and logout functionality. The <strong>LoginView<\/strong> and <strong>LogoutView<\/strong> handle the authentication process, reducing the need for custom code and simplifying these operations.<\/p><ol class=\"wp-block-list\">\n<li><strong>Set up URLs for login and logout<\/strong><\/li>\n<\/ol><p>Edit your <strong>urls.py<\/strong> file:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.urls import path\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n    path('login\/', auth_views.LoginView.as_view(), name='login'),\n    path('logout\/', auth_views.LogoutView.as_view(), name='logout'),\n]<\/pre><p>The <a href=\"\/tutorials\/django-url-patterns\">URL pattern<\/a> <strong>\/login\/<\/strong> is mapped to <strong>LoginView<\/strong>, which handles user login by displaying a login form and processing authentication.<\/p><p>Meanwhile, <strong>\/logout\/<\/strong> is mapped to <strong>LogoutView<\/strong>, which logs the user out, clears the session, and redirects them to the specified page.<\/p><ol start=\"2\" class=\"wp-block-list\">\n<li><strong>Create a login form template<\/strong><\/li>\n<\/ol><p>You can create a simple login template (<strong>login.html<\/strong>) inside your app&rsquo;s <strong>templates<\/strong> directory:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;form method=\"post\" action=\"{% url 'login' %}\"&gt;\n    {% csrf_token %}\n    &lt;div&gt;\n        &lt;label for=\"username\"&gt;Username:&lt;\/label&gt;\n        &lt;input type=\"text\" id=\"username\" name=\"username\" required&gt;\n    &lt;\/div&gt;\n    &lt;div&gt;\n        &lt;label for=\"password\"&gt;Password:&lt;\/label&gt;\n        &lt;input type=\"password\" id=\"password\" name=\"password\" required&gt;\n    &lt;\/div&gt;\n    {% if form.non_field_errors %}\n        &lt;div class=\"error\"&gt;\n            {{ form.non_field_errors }}\n        &lt;\/div&gt;\n    {% endif %}\n    &lt;button type=\"submit\"&gt;Login&lt;\/button&gt;\n&lt;\/form&gt;<\/pre><p>This template serves as a user interface for submitting login credentials. When paired with Django&rsquo;s built-in <strong>LoginView<\/strong>, it processes the username and password to authenticate the user.<\/p><ol start=\"3\" class=\"wp-block-list\">\n<li><strong>Create logout<\/strong><\/li>\n<\/ol><p>You don&rsquo;t need a separate template to log out, as Django&rsquo;s <strong>LogoutView<\/strong> handles it automatically. It clears the user session and redirects to the page defined in the <strong>LOGOUT_REDIRECT_URL<\/strong> setting, or a specified <strong>next_page<\/strong>.<\/p><p>To do so, simply add a logout link in your template:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;a href=\"{% url 'logout' %}\"&gt;Logout&lt;\/a&gt;<\/pre><h3 class=\"wp-block-heading\" id=\"h-create-user-registration-with-usercreationform\">Create user registration with UserCreationForm<\/h3><p>Django doesn&rsquo;t provide a built-in registration view by default, but you can create one using <strong>UserCreationForm<\/strong>. This Django form, provided in <strong>django.contrib.auth.forms<\/strong>, includes fields for <strong>username<\/strong>, <strong>password1<\/strong>, and <strong>password2<\/strong>, and handles validation for creating a new user.<\/p><ol class=\"wp-block-list\">\n<li><strong>Create a registration view<\/strong><\/li>\n<\/ol><p>In your <strong>views.py <\/strong>file, add:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.shortcuts import render, redirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login\nfrom django.contrib import messages\n\ndef register(request):\n    if request.method == 'POST':\n        form = UserCreationForm(request.POST)\n        if form.is_valid():\n            user = form.save()\n            login(request, user)\n            messages.success(request, \"Registration successful. Welcome!\")\n            return redirect('home')\n        else:\n            messages.error(request, \"Registration failed. Please check the form for errors.\")\n    else:\n        form = UserCreationForm()\n    return render(request, 'register.html', {'form': form})\n<\/pre><ol start=\"2\" class=\"wp-block-list\">\n<li><strong>Set up the URL for registration<\/strong><\/li>\n<\/ol><p>Include these lines in <strong>urls.py<\/strong>:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.urls import path\nfrom . import views  # Import your views module\n\nurlpatterns = [\n    path('register\/', views.register, name='register'),\n]\n<\/pre><ol start=\"3\" class=\"wp-block-list\">\n<li><strong>Create the registration form template<\/strong><\/li>\n<\/ol><p>For the <strong>register.html <\/strong>file, include:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;form method=\"post\"&gt;\n    {% csrf_token %}\n    {{ form.as_p }}\n    &lt;button type=\"submit\"&gt;Register&lt;\/button&gt;\n&lt;\/form&gt;\n<\/pre><p>This template displays a simple form rendered from Django&rsquo;s <strong>UserCreationForm<\/strong>. When paired with the registration view, it lets users create an account.<\/p><p>After successful registration, if the view includes a login step, users are automatically logged in and redirected to the specified page.<\/p><h3 class=\"wp-block-heading\" id=\"h-manage-user-sessions\">Manage user sessions<\/h3><p>Once users are logged in, manage their sessions to maintain security and ensure a smooth user experience.<\/p><p>Django uses the session framework to store data about each user&rsquo;s session on the server. This includes whether the user is logged in, their authentication state, and any additional session data you choose to save.<\/p><ol class=\"wp-block-list\">\n<li><strong>Access and modify session data<\/strong><\/li>\n<\/ol><p>Store, retrieve, and delete session data in Django views using the request.session dictionary-like object:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.shortcuts import render\n\ndef user_dashboard(request):\n    # Store data in session\n    request.session['welcome_message'] = 'Welcome back!'\n    \n    # Retrieve data from session\n    welcome_message = request.session.get('welcome_message', 'Hello, User!')\n\n    # Remove data from session\n    if 'welcome_message' in request.session:\n        del request.session['welcome_message']\n\n    return render(request, 'dashboard.html', {'message': welcome_message})<\/pre><ol start=\"2\" class=\"wp-block-list\">\n<li><strong>Customize session data<\/strong><\/li>\n<\/ol><p>Control session behavior by configuring the following settings in <strong>settings.py<\/strong>:<\/p><ul class=\"wp-block-list\">\n<li><strong>SESSION_COOKIE_AGE<\/strong> &ndash; determines how long a session lasts. By default, it&rsquo;s <strong>1209600<\/strong> seconds or <strong>2<\/strong> weeks.<\/li>\n\n\n\n<li><strong>SESSION_EXPIRE_AT_BROWSER_CLOSE<\/strong> &ndash; if set to <strong>True<\/strong>, sessions expire when the user closes the browser.<\/li>\n\n\n\n<li><strong>SESSION_ENGINE<\/strong> &ndash; specifies the session backend, such as database, cache, or file-based.<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># settings.py\nSESSION_COOKIE_AGE = 3600  # Sessions expire after 1 hour\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True  # Sessions expire on browser close\nSESSION_ENGINE = 'django.contrib.sessions.backends.db'  # Use database for sessions<\/pre><ol start=\"3\" class=\"wp-block-list\">\n<li><strong>Check authentication state<\/strong><\/li>\n<\/ol><p>Determine if a user is logged in using<strong> request.user.is_authenticated<\/strong>, useful for protecting views or displaying personalized content:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.shortcuts import redirect\n\ndef protected_view(request):\n    if not request.user.is_authenticated:\n        return redirect('login')  # Redirect to login if not authenticated\n    return render(request, 'protected_page.html')<\/pre><ol start=\"4\" class=\"wp-block-list\">\n<li><strong>End a session<\/strong><\/li>\n<\/ol><p>Log out users and clear their session data using the <strong>logout<\/strong> function:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth import logout\nfrom django.shortcuts import redirect\n\ndef logout_view(request):\n    logout(request)  # Logs out the user and clears session data\n    return redirect('login')  # Redirect to login page\n<\/pre><h2 class=\"wp-block-heading\" id=\"h-how-to-customize-django-user-model\">How to customize Django User model<\/h2><p>In some cases, Django&rsquo;s default <strong>User<\/strong> model may not meet all the requirements of your application. Customizing the user model lets you add fields, change authentication behavior, or replace the <strong>User<\/strong> model entirely with one tailored to your needs.<\/p><h3 class=\"wp-block-heading\" id=\"h-abstractbaseuser-vs-abstractuser\">AbstractBaseUser vs. AbstractUser<\/h3><p>When customizing the user model, you have two primary options: extending from <strong>AbstractBaseUser<\/strong> or <strong>AbstractUser<\/strong>.<\/p><p><strong>AbstractBaseUser <\/strong>provides the bare minimum: password hashing and authentication features. It gives you full control to define all fields and behaviors, including <strong>username<\/strong>, <strong>email<\/strong>, or any additional data you need.<\/p><p>However, it requires you to implement fields and methods such as <strong>USERNAME_FIELD<\/strong>, <strong>is_active<\/strong>, and <strong>objects<\/strong>.<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.models import AbstractBaseUser, BaseUserManager\nfrom django.db import models\n\nclass CustomUserManager(BaseUserManager):\n    def create_user(self, email, password=None, **extra_fields):\n        if not email:\n            raise ValueError('Email address is required')\n        email = self.normalize_email(email)\n        user = self.model(email=email, **extra_fields)\n        user.set_password(password)\n        user.save(using=self._db)\n        return user\n\nclass CustomUser(AbstractBaseUser):\n    email = models.EmailField(unique=True)\n    first_name = models.CharField(max_length=30)\n    last_name = models.CharField(max_length=30)\n    is_active = models.BooleanField(default=True)\n    is_staff = models.BooleanField(default=False)\n\n    USERNAME_FIELD = 'email'\n    REQUIRED_FIELDS = ['first_name', 'last_name']\n\n    objects = CustomUserManager()\n<\/pre><p><strong>AbstractUser<\/strong> inherits from <strong>AbstractBaseUser<\/strong> and includes all fields and methods of the default User model, such as <strong>username<\/strong>, <strong>email<\/strong>, <strong>first_name<\/strong>, and <strong>last_name<\/strong>. It&rsquo;s ideal if you only need to add extra fields or slightly modify existing behavior without rewriting the entire model.<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\nclass CustomUser(AbstractUser):\n    age = models.PositiveIntegerField(null=True, blank=True)<\/pre><h3 class=\"wp-block-heading\" id=\"h-create-a-custom-user-model\">Create a custom user model<\/h3><p>To define a custom user model, follow these steps:<\/p><ol class=\"wp-block-list\">\n<li>Define a custom user model extending from <strong>AbstractBaseUser<\/strong> or <strong>AbstractUser<\/strong>.<\/li>\n\n\n\n<li>Specify your custom user model in <strong>settings.py<\/strong>:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">AUTH_USER_MODEL = 'myapp.CustomUser'<\/pre><ol start=\"3\" class=\"wp-block-list\">\n<li>Custom user models require a custom manager to handle user creation, <strong>create_user<\/strong> and <strong>create_superuser<\/strong>.<\/li>\n\n\n\n<li>Use <strong>UserCreationForm<\/strong> and <strong>UserChangeForm<\/strong> from <strong>django.contrib.auth.forms<\/strong> as bases for creating <a href=\"\/tutorials\/django-forms\">forms<\/a> compatible with your custom user model:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom .models import CustomUser\n\nclass CustomUserCreationForm(UserCreationForm):\n    class Meta:\n        model = CustomUser\n        fields = ['email', 'first_name', 'last_name']\n\nclass CustomUserChangeForm(UserChangeForm):\n    class Meta:\n        model = CustomUser\n        fields = ['email', 'first_name', 'last_name']<\/pre><h3 class=\"wp-block-heading\" id=\"h-migrate-to-a-custom-user-model-in-an-existing-project\">Migrate to a custom user model in an existing project<\/h3><p>Switching to a custom user model in an existing project can be challenging, as Django&rsquo;s authentication system tightly integrates with the default <strong>User<\/strong> model. Here are the steps:<\/p><ol class=\"wp-block-list\">\n<li>Back up your database to avoid losing data during migration.<\/li>\n\n\n\n<li>Define your custom model and update the <strong>AUTH_USER_MODEL<\/strong> setting in <strong>settings.py<\/strong>.<\/li>\n\n\n\n<li>If the project already has a <strong>User<\/strong> model and associated data, you&rsquo;ll need to handle the migration process carefully:\n<ul class=\"wp-block-list\">\n<li>Create a data migration script to copy data from the old <strong>auth.User<\/strong> model to your new custom user model.<\/li>\n\n\n\n<li>Use <strong>makemigrations<\/strong> and <strong>migrate<\/strong> commands to apply the changes.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Update any models, views, or forms that reference the default <strong>User<\/strong> model to point to your custom model using <strong>get_user_model()<\/strong>:<\/li>\n<\/ol><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth import get_user_model\n\nUser = get_user_model()<\/pre><ol start=\"5\" class=\"wp-block-list\">\n<li>Thoroughly test all authentication features, including login, logout, and password reset. Make sure they work seamlessly with the new user model.<\/li>\n<\/ol><h2 class=\"wp-block-heading\" id=\"h-managing-user-permissions-and-authorization\">Managing user permissions and authorization<\/h2><p>Django lets you assign different permissions to individual users and groups, enabling role-based access control.<\/p><h3 class=\"wp-block-heading\" id=\"h-control-user-authorization-with-django-s-built-in-permissions\">Control user authorization with Django&rsquo;s built-in permissions<\/h3><p>You can assign permissions to user models or groups and check within your views to control access to specific actions and define their roles.<\/p><p>For example, an admin might have permissions to add or delete content, while regular users can only view content.<\/p><h3 class=\"wp-block-heading\" id=\"h-restrict-views-based-on-permissions\">Restrict views based on permissions<\/h3><p>You can restrict access to certain views by checking if a user has the required permissions using Django&rsquo;s <strong>@permission_required<\/strong> decorator. For example:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.decorators import permission_required\n\n@permission_required('app.add_article')\ndef add_article(request):\n    # View code for adding an article<\/pre><p>Only users with the <strong>add_article<\/strong> permission will be able to access this view.<\/p><h3 class=\"wp-block-heading\" id=\"h-implement-role-based-access-control-rbac-with-groups\">Implement role-based access control (RBAC) with groups<\/h3><p>Django&rsquo;s <strong>Group<\/strong> feature lets you implement role-based access control by creating roles such as editor or viewer and associating users with these groups. You can give groups specific permissions, which all their members automatically inherit.<\/p><ol class=\"wp-block-list\">\n<li><strong>Assign users to groups<\/strong><\/li>\n<\/ol><p>To assign a user to a group programmatically, use the <strong>Group<\/strong> and <strong>User<\/strong> models as shown below:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.models import Group, User\n\n# Retrieve the group and user\ngroup = Group.objects.get(name='editors')\nuser = User.objects.get(username='john')\n\n# Assign the user to the group\nuser.groups.add(group)\n<\/pre><p>If the group doesn&rsquo;t exist, you can create it programmatically:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">group, created = Group.objects.get_or_create(name='editors')<\/pre><ol start=\"2\" class=\"wp-block-list\">\n<li><strong>Check group membership in views<\/strong><\/li>\n<\/ol><p>You can restrict views based on group membership by using the <strong>@user_passes_test<\/strong> decorator. The example below demonstrates how to limit access to a view for users in the <strong>editors<\/strong> group:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.decorators import user_passes_test\nfrom django.shortcuts import render\n\n# Define a test function to check group membership\ndef is_editor(user):\n    return user.groups.filter(name='editors').exists()\n\n# Restrict access to the editor_dashboard view\n@user_passes_test(is_editor, login_url='\/login\/')  # Redirect unauthorized users to login\ndef editor_dashboard(request):\n    return render(request, 'editor_dashboard.html')\n<\/pre><p>In this example, only users who belong to the <strong>editors<\/strong> group can access the <strong>editor_dashboard<\/strong> view. Unauthorized users are redirected to the login page (<strong>\/login\/<\/strong>), but you can customize this URL as needed.<\/p><h2 class=\"wp-block-heading\" id=\"h-working-with-django-s-authentication-backends\">Working with Django&rsquo;s authentication backends<\/h2><p>Authentication backends in Django determine how users are authenticated and how permissions are retrieved. By default, Django uses the <strong>ModelBackend<\/strong>, which authenticates against the <strong>User<\/strong> model and checks permissions stored in the database.<\/p><h3 class=\"wp-block-heading\" id=\"h-1-create-a-custom-authentication-backend\">1. Create a custom authentication backend<\/h3><p>You can create a custom authentication backend to implement alternative login methods, such as email-based authentication or third-party services. A custom backend must define at least two methods:<\/p><ul class=\"wp-block-list\">\n<li><strong>authenticate(self, request, **credentials)<\/strong><\/li>\n\n\n\n<li><strong>get_user(self, user_id)<\/strong><\/li>\n<\/ul><p>Here&rsquo;s an example of creating a custom backend to allow login with an email address:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth.models import User\n\nclass EmailBackend:\n    def authenticate(self, request, username=None, password=None, **kwargs):\n        try:\n            user = User.objects.get(email=username)  # Authenticate using email\n            if user.check_password(password):\n                return user\n        except User.DoesNotExist:\n            return None\n\n    def get_user(self, user_id):\n        try:\n            return User.objects.get(pk=user_id)\n        except User.DoesNotExist:\n            return None\n<\/pre><p>Add this backend to your <strong>AUTHENTICATION_BACKENDS<\/strong> setting:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">AUTHENTICATION_BACKENDS = [\n    'myapp.backends.EmailBackend',\n    'django.contrib.auth.backends.ModelBackend',  # Fallback to username authentication\n]\n<\/pre><h3 class=\"wp-block-heading\" id=\"h-2-work-with-permissions-in-custom-backends\">2. Work with permissions in custom backends<\/h3><p>Custom backends can also define how permissions are retrieved for users by overriding <strong>has_perm<\/strong>, <strong>has_module_perms<\/strong>, or similar methods. For instance:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def has_perm(self, user, perm, obj=None):\n    # Custom permission logic\n    return True  # Grant all permissions for demonstration purposes\n<\/pre><h3 class=\"wp-block-heading\" id=\"h-3-debug-authentication-issues\">3. Debug authentication issues<\/h3><p>Django supports multiple authentication backends, which showed in the <strong>AUTHENTICATION_BACKENDS <\/strong>snippet. However, you might find issues when using multiple backends. To debug:<\/p><ul class=\"wp-block-list\">\n<li>Check the logs to see which backend is being called.<\/li>\n\n\n\n<li>Use <strong>django.contrib.auth.authenticate()<\/strong> manually in the shell to test credentials:<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">from django.contrib.auth import authenticate\nuser = authenticate(username='john@example.com', password='securepassword')\nprint(user)\n<\/pre><h2 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h2><p>Understanding and customizing Django&rsquo;s <strong>User<\/strong> model is important for building strong authentication systems. With flexible tools for creating custom user models, managing sessions, permissions, and authentication backends, Django supports diverse requirements.<\/p><p>You can implement role-based access control, restrict views, and tailor authentication methods to provide a secure and user-friendly experience. Mastering these features lets you manage users confidently in any Django application.<\/p><h2 class=\"wp-block-heading\" id=\"h-django-user-models-faq\">Django user models FAQ<\/h2><div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1732613439238\"><h3 class=\"schema-faq-question\">How do I create a custom user model in Django?<\/h3> <p class=\"schema-faq-answer\">To create a custom user model in Django, subclass <strong>AbstractUser<\/strong> or <strong>AbstractBaseUser<\/strong>, add desired fields, and set <strong>AUTH_USER_MODEL<\/strong> in <strong>settings.py<\/strong>. To avoid conflicts, do this before initial migrations. This setup allows for custom user attributes and flexible authentication.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1732613448354\"><h3 class=\"schema-faq-question\">What fields are included in the default Django User model?<\/h3> <p class=\"schema-faq-answer\">The default Django <strong>User<\/strong> model includes <strong>username<\/strong>, <strong>password<\/strong>, <strong>email<\/strong>, <strong>first_name<\/strong>, and <strong>last_name<\/strong> for basic user information; <strong>is_staff<\/strong>, <strong>is_active<\/strong>, and <strong>is_superuser<\/strong> for role management; and <strong>last_login<\/strong> and <strong>date_joined<\/strong> for activity tracking.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1732613452171\"><h3 class=\"schema-faq-question\">How do I extend the default User model?<\/h3> <p class=\"schema-faq-answer\">Extend Django&rsquo;s default <strong>User<\/strong> model by creating a new model with a <strong>OneToOneField(User)<\/strong>. Add custom fields in this model to store additional data, keeping the original user model intact while allowing access to extended attributes through the user instance.<\/p> <\/div> <\/div><p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Django&nbsp;User&nbsp;model provides a solid foundation for managing users, securing content, and controlling access to your web applications. As you [&#8230;]<\/p>\n<p><a class=\"btn btn-secondary understrap-read-more-link\" href=\"\/tutorials\/django-user-model\">Read More&#8230;<\/a><\/p>\n","protected":false},"author":185,"featured_media":118890,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"How to use Django user model for authentication","rank_math_description":"Learn how to implement and customize the Django user model for authentication, registration, and authorization in your web applications.","rank_math_focus_keyword":"django user model","footnotes":""},"categories":[22646,22644],"tags":[],"class_list":["post-119328","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-pre-installed-applications","category-vps"],"hreflangs":[{"locale":"en-US","link":"https:\/\/www.hostinger.com\/tutorials\/django-user-model","default":0},{"locale":"en-UK","link":"https:\/\/www.hostinger.com\/uk\/tutorials\/django-user-model","default":0},{"locale":"en-MY","link":"https:\/\/www.hostinger.com\/my\/tutorials\/django-user-model","default":0},{"locale":"en-PH","link":"https:\/\/www.hostinger.com\/ph\/tutorials\/django-user-model","default":0},{"locale":"en-IN","link":"https:\/\/www.hostinger.com\/in\/tutorials\/django-user-model","default":0},{"locale":"en-CA","link":"https:\/\/www.hostinger.com\/ca\/tutorials\/django-user-model","default":0},{"locale":"en-AU","link":"https:\/\/www.hostinger.com\/au\/tutorials\/django-user-model","default":0},{"locale":"en-NG","link":"https:\/\/www.hostinger.com\/ng\/tutorials\/django-user-model","default":0}],"_links":{"self":[{"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/posts\/119328","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/users\/185"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/comments?post=119328"}],"version-history":[{"count":12,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/posts\/119328\/revisions"}],"predecessor-version":[{"id":128698,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/posts\/119328\/revisions\/128698"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/media\/118890"}],"wp:attachment":[{"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/media?parent=119328"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/categories?post=119328"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hostinger.com\/tutorials\/wp-json\/wp\/v2\/tags?post=119328"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}