Social Icons

Saturday, January 15, 2022

User authentication in django

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

No comments:

Post a Comment

Learn Python For Beginners

Category Of Mobile Courses

Actualités (644) Adsense (1) Affiliation (1) Algebraic Topology (2) Algorithmic (1) all-news (30) Android (5) Android App (8) Android app without code (4) Android Apps (256) Android Development (4) Android download (2) Android OS (3) AngularJS (1) Automata theory and formal language (5) Bootstrap CSS (1) C programming (5) Category and Functor (8) CMS (3) Computer Glossary (18) Create Mobile App With Ionic Framework (2) CSS (2) CSS-Cascading-Style-Sheets (4) Developpement Java (13) Differential Geometry (1) Django-Python-Framework (15) dropshiping (26) Earn Money by Internet (4) Emplois (23) Framework php (2) Fraud (2) Github (2) HTML (7) IT News (3) Java For Beginners (10) Javascript (12) Kotlin Programming Language (8) Kotlin For Mobile Android (1) Linux Download (2) Marketing (5) Mobile (3) Mobile Courses (4) Mobile Marketing (4) MoneyGram (1) News (721) Node.js (5) Open Source (1) Photoshop (1) Protect Computer (1) Python (36) Python BeautifulSoup (1) Python For Data Science (2) Python PyQt (13) Python Reference (1) Python Source Code (3) Python-Books (6) Python-DVD-Training (1) Python-Exercises (297) Python-Framework (1) Python-IDE (1) Python-Kivy-Framework (2) Python-Modules (1) Python-pdf (2) Python-pyQt (1) python-temp (3) Référencement (2) Script PHP (2) Security (6) SEO (1) Snipping Tool: Faq (1) Social Networks (1) Source Code (4) Statistics With SPSS (2) Surveillance Software (1) Travail à domicile (6) Tutoriels php en vidéos (2) Tutoriels-MySql (6) tutoriels-php (19) Utilitaires (1) VPS (1) Web Hosting (1) Webcam (1) Webmarketing (11) Western Union (1) Windows 10 (1) Windows 7 (4) Windows 7 Faq (2) Windows 8 (1) Windows Accessories (1) Windows Download (8) Windows Drivers (1) Windows Fonts (1) Windows Power Shell (2) Windows Registry (2) Windows Security (18) Windows Software (2) Windows Spyware (2) Windows utilities (3) Windows Virus (2) Windows Vista (3) Windows Wireless (1) Windows xp (1) Wordpress (1)
 

Sample text

Sample Text

 
Blogger Templates