11 minutes read

To access the service's customization, users should have personal accounts so that they can perform actions related only to them: for example, save personal preferences, post articles, or make purchases.

If you are an active Internet user, you're probably familiar with the sign-up, login, and logout operations. Django provides the means to add those operations easily. In this topic, you will learn how to add registration and authentication to a service.

User model

To distinguish one user from another, we need to store their identification information on the server. On websites, it's usually a unique username or email address. Both characteristics may be stored in the default User model.

To start working with the User model, run python manage.py migrate from the root of your project. If you don't change any settings, you will have an SQLite database attached to your project.

After making the initial migrations, you can create new accounts. Typically, clients of your service will create their own accounts, but let's explore how you can manually create a regular user or a superuser in the database using the console.

A superuser is an administrative account for your service. As a superuser, you have access to and can manipulate any data in the database. Regular users, on the other hand, can only manipulate their own data.

To use an initialized console client, run python manage.py shell command.

from django.contrib.auth.models import User


User.objects.create_superuser(
   username='admin', email='[email protected]', password='SeCreTPaSsWorD'
)

User.objects.create_user(
   username='usual_user', email='[email protected]', password='NotSecRetAtAll'
)

As you may have guessed, create_user method creates a usual user and create_superuser creates a superuser in your database. You're not likely to need the create_user method often, but you will need a console method to make the first admin account.

Another way to create a superuser is with the python manage.py createsuperuser command. You can read more about it in the official Django documentation.

Similar to superuser, Django also provides a user object called staff. A staff is a user in Django that has access to the admin panel but has no permission to create, delete or modify anything present on the panel. On the other hand, the superuser is the absolute administrator of any Django project and has full access to the model present on the admin panel.

So to sum up the user privileges:

  1. Normal users can only access the interface provided in the front end and cannot access the admin panel.

  2. Staff users can access the admin panel. They can see the models but beyond this, they have no privilege. Some staff can be given the privilege to manage certain models which have to be defined explicitly.

  3. Superuser has access to all the models and can change them freely without restrictions. A superuser is granted all the permissions in a Django project.

Preparing URLs

To separate each action, you should choose the URL addresses for login, logout, and signup operations. You should update the urlpatterns variable in your main urls.py module.

To make it neat and clear, choose straightforward paths:

urlpatterns += [
    path('login', MyLoginView.as_view()),
    path('logout', LogoutView.as_view()),
    path('signup', MySignupView.as_view()),
]

Now you need to implement several classes and import them to the urls.py module. Start by making MySignupView class.

Signup

You already know how you can create a new user with Python, but regular users don't know Python. We've got to provide a simple web interface for them with an HTML form. Fortunately, making it will only take us a few simple steps, and then your new users will just sign up on their own.

from django.contrib.auth.forms import UserCreationForm
from django.views.generic import CreateView


class MySignupView(CreateView):
    form_class = UserCreationForm
    success_url = 'login'
    template_name = 'signup.html'

To be able to create objects with the HTTP handler, we inherit MySignupView class from CreateView. We define several attributes that will do the work for us:

  • The form_class attribute is a Django form class. We select UserCreationForm from the framework to create a new user.

  • After our users finished registration, they are redirected to the success_url page of the service, in our case, to the login page.

  • template_name is simply the name of a template responsible for the signup page of the service.

We're almost there with preparing our registration form; just add a custom signup.html template and that's it.

<form method="post" action="signup">{% csrf_token %}
  <table>{{ form.as_table }}</table>
  <button type="submit">Send</button>
</form>

Do not forget to update settings.TEMPLATES.DIRS and add the signup.html template's directory to it.

We make a simple form and add it to the template, which is enough for a quick start. The page is cluttered with hints, but it does the job well. Now we have a registration form for the service:

Registration form

Login

The process of creating a request handler for logging in is very similar to making a registration form. We define the class and specify the template_name in it:

from django.contrib.auth.views import LoginView


class MyLoginView(LoginView):
    redirect_authenticated_user = True
    template_name = 'login.html'

This time we add another attribute redirect_authenticated_user and set it to True. All authenticated users that come back to the login page will be redirected to the main site instead of having to fill the authentication form again.

To define where the user should be redirected after successful authentication, we set LOGIN_REDIRECT_URL = '/' in the settings.py module. It's usually the main page of the service, but you can choose any page you like.

The login.html template differs from signup.html by the action field and the label of the button:

<form method="post" action="login">{% csrf_token %}
  <table>{{ form.as_table }}</table>
  <button type="submit">Login</button>
</form>

The result is concise and pleasing:

Authentication form

Logout

The last action our users need is logout. They do not need to send any information, so to log out they should just go to the right URL.

You can see that for login and signup we define our custom MySignupView and MyLoginView classes accordingly. In urlpatterns you can find that for logout we use LogoutView class from django.contrib.auth.views module. Just import it to the urls.py module to complete the work.

If you want to specify where the user should be redirected after logging out, you can define this in the settings.py module. For example, to redirect users back to the login page, add this line to the module: LOGOUT_REDIRECT_URL = '/login'.

Now you know enough to add authentication to any service, so you can personalize your web service for each individual user.

Conclusion

Now you are familiar with user registration and authentication. To summarize the entire topic:

  1. Django provides a user model of three permission levels: Normal user, Staff user and Super user

  2. To register a new user, you can create an instance of the User model from django.contrib.auth.models.

  3. For logging in, you need to authenticate a User.

  4. Logging out is the simplest part of User-application interaction and the generic view can be used for the purpose.

5 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo