How to register as an admin in Django app using Registration Model and Views.py?

1.2k Views Asked by At

I am familiar with creating a superuser in a Django App using python manage.py createsuperuser command in terminal. I am also familiar with creating a superuser using Python Shell.

But I want to know that how do we register a user as an admin in a Django App using RegistrationModel and views.py? Or more specifically, how to register the user and change it's status to staff or superuser in views.py?

1

There are 1 best solutions below

0
Ridwan On

STEP ONE

After creating and activating virtual environment Let's create our new project (authentication) and a new app (users) using the following command

    $ django-admin startproject authentication . 
    $ python manage.py startapp users

Next is we add users app to installed_apps in authentication/settings.py file

STEP TWO

We create CustomUser model in our users/urls.py file

    #users/urls.py
    from django.contrib.auth.models import AbstractUser
    from django.urls import reverse

    class CustomUser(AbstractUser):
        pass

    def get_absolute_url(self):
        return reverse("login_page", args=[str(self.id)])

In other to alert django to use the CustomUser model for authentication, we add AUTH_USER_MODEL = 'users.CustomUser' to our authentication/settings.py file

STEP THREE

Create a new file forms.py in users app and add the following

    from django.contrib.auth.forms import UserChangeForm, UserCreationForm
    from .models import CustomUser

    class CustomUserCreationForm(UserCreationForm):
        class Meta(UserCreationForm.Meta):
            model = CustomUser
            fields = [
                'first_name',
                'last_name',
                'username',
                'email',
                'password1',
                'password2',
                'is_staff',
                'is_superuser',
            ]
        
    class CustomUserChangeForm(UserChangeForm):
        class Meta:
            model = CustomUser
            fields = UserChangeForm.Meta.fields

STEP FOUR

Since we customized our UserCreationForm and UserChangeForm, we have to update in our users/admin.py file

from django.contrib import admin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
from django.contrib.auth.admin import UserAdmin

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    list_display = [
            'first_name',
            'last_name',
            'email',
            'is_staff',
            'is_superuser',
        ]    

admin.site.register(CustomUser, CustomUserAdmin)

STEP FOUR

We can proceed to making migrations and migrating the tables to database using the command

    $ python manage.py makemigrations
    $ python manage.py migrate

STEP FIVE

Create the template for creating new users. We create a new folder (templates) in our parent dir where we can store our html files and create a new file create_new.html in the templates folder

Command for this:

    $ mkdir templates
    $ touch templates/create_new.html

Update the templates settings

    # authentication/settings.py
    TEMPLATES:
         'DIRS': [BASE_DIR/'templates']  # new

Add the following to templates/create_new.html file

    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial- 
    scale=1.0">
        <title>New admin</title>
    </head>

    <body>
        <form method="post">
            {% csrf_token %} {{ form.as_p }}
        <input type="submit" value="Create new user" />
        </form>
    </body>

    </html>

STEP SIX

Create view to display this template

    # users/views.py
    from django.views.generic.edit import CreateView
    from .models import CustomUser
    from .forms import CustomUserCreationForm

    class UserCreateView(CreateView):
        model = CustomUser
        template_name = 'create_new.html'
        form_class = CustomUserCreationForm

STEP SEVEN

Link view to a specific url

    # authentication/urls.py
    from django.contrib import admin
    from django.urls import path, include # new

    urlpatterns = [
        path('admin/', admin.site.urls,),
        path('', include('users.urls')), # new
    ]
#user/urls.py
from django.urls import path
from .views import UserCreateView

urlpatterns = [
    path('', UserCreateView.as_view(), name='home'),
]

STEP EIGHT

Run local server and create new user to login to the admin-site. *No need of python manage.py createsuperuser command