1 - Create a new django project with an app named accounts

To start we proceed by: 

- creating of a new project named mysite
- migration and creation of a super user account
- creating of a new app called accounts

 

Next, let's register our accounts application at the settings.py file:

INSTALLED_APPS = [
'accounts.apps.AccountsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Our site will therefore have the following structure: 

Next, let's configure the template:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Next, let's create the template files by creating:  

1- the template home page file  "template/index.html"
2- the'registration' directory within the template directory
3- the files:
     - 3.a template/registration/login.html
    - 3.b template/registration/logout.html
     - 3.c template/registration/signup.html
 

 As shown in the following figure: 

 

2 - Creation of a system login & logout

2.1 - Using the auth app

When creating a new project, django automatically creates an application named

auth

, as you can see from the

settings.py

file:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
]

To use the

auth

app we must to add it to our project level file

urls.py

:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
]

The

auth

app that installs automatically with a new django project has multiple

authentication views

and urls for managing

login

,

logout

, and

password

management. The URLs provided by auth are:

accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']

2.2 - Login and logout page

Now we create the "template/registration/login.html" file which will be used by the

auth

module to

connect

a user:

<!-- templates/registration/login.html -->
# we test if the user is authenticated
{% if user.is_authenticated %}
You are connected as <strong> {{ user.username }}!</strong>
<a href="/accounts/logout" >Logout !</a>
# if user is not authenticated, we display the authentication form:
{% else %}
<h3>Log In</h3>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
</form>
{% endif %}

Now if we type in the browser, the url address: http://127.0.0.1:8000/accounts/login/ we obtain the user athenication form: 

And if we type the url address http://127.0.0.1:8000/accounts/logout/  we obtain this message indicating that the user is logged out:

 

2.3 - Settings up home page

We can now configure the home page so that it displays a welcome message to the user when he is connected and otherwise a message indicating that he is not connected followed by a link to the login page. Let's start with the configuration of the template file:

<!-- templates/index.html -->
<h2>Home Page !</h2>
{% if user.is_authenticated %}
Hi {{ user.username }}!
<p><a href="{% url 'logout' %}">Log Out</a></p>
{% else %}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Log In</a>
{% endif %}

In order to display the home page we will create a link to it using the TemplateView class:

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/' , include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='home'),
]

And finally redirects to the home page after login or logout:

LOGOUT_REDIRECT_URL = '/'
LOGIN_REDIRECT_URL = '/'

Now if we type the url address : http://127.0.0.1:8000/ we obtain: 

 

 

And after connection: 

 

3 - User registration form

3.1 - Creation of the registration form via the UserCreationForm class

Let's now create the

accounts/forms.py

file which will generate the user

registration form

and insert within it the following code:

# accounts/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
email = forms.EmailField()

class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']

3.2 - Creation the view of accounts applications

We then create the view of application which has a method for the user registration form

# accounts/views.py
from django.shortcuts import render, redirect
from .forms import UserRegisterForm

# Users registration page
def signup(request):
# on teste s'il y a des requetes envoyee par la methode POST
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
return redirect('/')
else:
form = UserRegisterForm()
return render(request, 'registration/signup.html', {'form': form})

Then update the url system

# mysite/urls
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView
from accounts import views

urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/' , include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='index.html'), name='home'),
path('signup/' , views.signup , name ='signup'),
]

And finally we build the template file:

<!-- templates/registration/signup.html -->
<h2>Registration form</h2>
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Register</button>
</div>
</form>

Now if we type in the browser the url address: http://127.0.0.1:8000/signup/ we obtain the registration form:

Younes Derfoufi
my-courses.net

Leave a Reply