David J Nevin+= Code

Published: Sep 19, 2022

Django Users, Login & Registration

The user functionality is created in a seperate app. This project uses built-in user functionality to keep things managable for my first attempts.

Create a new app

As in the previous section a new app is created using the startapp command, in this case the app name is users.

100
python manage.py startapp users

To complete the app creation process we create the following files and folders.

urls.py, forms.py and a folder registration, inside a folder named templates.

Inside the registration folder we create two html files, register.html and login.html.

All of these files and folders are created inside the users folder.

The registration folder is specifically required with the use of the django built-in system for authentication.

Register the new app

The new app needs to be registered in the project settings.py

100
101
102
103
104
105
106
107
108
109
110
111
112
...

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'listings_app',
    'users'
]
...

And the path to the app nees to be added to the the project urls.py file.

100
101
102
103
104
105
106
107
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('listings.urls')),
    path('users/', include('users.urls')),
]

Login page

Since this project uses the bulit-in django authentication system, the users urls.py file uses the django.contrib.auth package.

100
101
102
103
104
105
106
107
from django.urls import path, include
from .import views

app_name = 'users'

urlpatterns = [
    path('', include('django.contrib.auth.urls')),
]

A login view is provided by the built-in system.

Login template

The login template is a simple form and redirects to the homepage upon completion.

100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
{% extends "listings/base.html" %}

{% block content %}
<h1 class="text-center">Login</h1>

<form method="POST" action="{% url 'users:login' %}">
    {% csrf_token %}
    {{ form.as_p}}

    <button name="submit" class="btn">Log in</button>
    <input type="hidden" name="next"
    value="{% url 'listings:index' %}" />
</form>

{% endblock content %}

It is possible to create a non-standard logout page, by adding a log_out path to the users urls.py page. This will call the views.py log_out function as opposed to the built in. In this way we can set the desired redirect path after logout.

urls.py

100
101
102
...
path('log_out/', views.log_out, name='log_out'),
...

And the function in the app’s views.py.

100
101
102
103
104
105
106
from django.shortcuts import render, redirect
from django.contrib.auth import logout


def log_out(request):
    logout(request)
    return redirect('listings:index')

This results in the user, once logout out, being directed to the homepage and not the standard django logout screen.

Registration

The registration proceedure contains, an addition to the urls.py

100
path('register/', views.register, name='register'),

The views.py makes use of the standard built-in functionality.

100
101
102
103
104
105
106
107
108
109
110
def register(request):
    if request.method != 'POST':
        form = UserForm()
    else:
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('users:login')

    context = {'form': form}
    return render(request, 'registration/register.html', context)

This a is rudimentary registration page. It doesn’t offer any confirmation of email address and is immediately active. It imports from the users app folder the UserForm() function from forms.py

100
101
102
103
104
105
106
107
108
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class UserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

This in turn imports the UserCreationForm form the standard built-in.

An example of a simple registration form.

100
101
102
103
104
105
106
107
108
109
110
111
112
113
{% extends "listings/base.html" %}

{% block content %}

<h1>Create Account</h1>
<form method="post" action="{% url 'users:register' %}">
   {% csrf_token %}
   {{ form.as_p}}

   <button name="submit" class="btn">Register</button>
   <input type="hidden" name="next" value="{% url 'users:login' %}" />
</form>

{% endblock content %}

That’s a basic overview of the user, loging and registration setup using the Django built-in.


Next: Pipenv to Poetry
Previous: Django Delete Items