article

Sunday, June 14, 2020

Django Authentication Sign Up, Login, Logout and Protecting Views


Django Authentication Sign Up, Login, Logout and Protecting Views


In this tutorial  we are going to explore Django’s authentication system by implementing sign up, login, logout, and protected views from non-authenticated users.

Official documentation information: Using the Django authentication system https://docs.djangoproject.com/en/2.1/topics/auth/default/

views.py
 
#views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin

def home(request):
    count = User.objects.count()
    return render(request, 'home.html', {
        'count': count
    })

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'registration/signup.html', {
        'form': form
    })
 
@login_required
def secret_page(request):
    return render(request, 'secret_page.html')
 
class SecretPage(LoginRequiredMixin, TemplateView):
    template_name = 'secret_page2.html'
urls.py
 
#urls.py
from django.contrib import admin  
from django.urls import path
from myapp import views  
from django.conf.urls import url
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('signup/', views.signup, name='signup'),
    path('secret/', views.secret_page, name='secret'),
    path('secret2/', views.SecretPage.as_view(), name='secret2'),
    path('accounts/', include('django.contrib.auth.urls')),
]
templates/home.html
#templates/home.html
{% extends 'base.html' %}

{% block content %}
  <h2>Homepage</h2>
  <p>Welcome to My Site, {% if user.is_authenticated %}{{ user.username }}{% else %}visitor{% endif %}!</p>
  <p>
    <strong>Total users registered: </strong> {{ count }}
  </p>
{% endblock %}
templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django Authentication Sign Up, Login, Logout and Protecting Views{% endblock %}</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="{% url 'home' %}">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
      {% if user.is_authenticated %}
   <a class="nav-item nav-link active" href="{% url 'home' %}">Home <span class="sr-only">(current)</span></a>
      <a class="nav-item nav-link" href="{% url 'home' %}">Hello : {{ user.username }}</a>
      <a class="nav-item nav-link" href="{% url 'logout' %}">Log out</a>
   {% else %}
      <a class="nav-item nav-link" href="{% url 'login' %}">Log in</a>
      <a class="nav-item nav-link" href="{% url 'signup' %}">Sign up</a>
   {% endif %}
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">Django Authentication Sign Up, Login, Logout and Protecting Views</h3>
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div>
 <style type="text/css">
    .asteriskField {
      display: none;
    }

    form .alert ul li {
      list-style: none;
    }

    form .alert ul {
      padding: 0;
      margin: 0;
    }
  </style> 
</body>
</html>
templates/signup.html
//templates/signup.html
{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <div class="row justify-content-center">
    <div class="col-8">
      <div class="card">
        <div class="card-body">
          <h2>Sign Up</h2>
          <form method="post">
            {% csrf_token %}
            {{ form|crispy }}
            <button type="submit" class="btn btn-primary">Sign up</button>
          </form>
        </div>
      </div>
    </div>
  </div>
{% endblock %}
templates/registration/login.html
//templates/registration/login.html
{% extends 'base.html' %}

{% load crispy_forms_tags %}

{% block content %}
  <div class="row justify-content-center">
    <div class="col-6">
      <div class="card">
        <div class="card-body">
          <h2>Log in</h2>
          <form method="post" novalidate>
            {% csrf_token %}
            {{ form|crispy }}
            <button type="submit" class="btn btn-primary">Log in</button>
          </form>
        </div>
      </div>
    </div>
  </div>
{% endblock %}
templates/secret_page.html
//templates/secret_page.html
{% extends 'base.html' %}

{% block content %}
  <p>This is a Protected Page!</p>
{% endblock %}
templates/secret_page2.html
//templates/secret_page2.html
{% extends 'base.html' %}

{% block content %}
  <p>This is a Protected Page 2!</p>
{% endblock %}
settings.py add to setting.py 'crispy_forms', INSTALLED_APPS

Related Post