Home

Boilerplate: Add Basic User Authencation To A Django Site

Introduction

This process sets up for basic user authentication. It's designed to be run after going through Boilerplate: Create A New Django Site/Project and Boilerplate: Add Basic Template And Static File Handling In Django .

Boilerplate Steps

  1. Make sure you've started the Python venv and are in the directory with: manage.py

    TODO: Write up how to make sure you're in the proper venv

  2. Make the directory to hold the necessary templates:

    terminal commands
    mkdir -p templates/registration
  3. Add login/logout default redirects to the bottom of the site_files/settings.py file

    site_files/settings.py - append to end of file
    LOGIN_REDIRECT_URL = "/"
    LOGOUT_REDIRECT_URL = "/"
  4. Add the includes import and auth include to site_files/urls.py. The file should look like this:

    site_files/urls.py - full content replacement
    from django.contrib import admin
    from django.urls import path
    from django.urls import include
    
    urlpatterns = [
        path("accounts/", include("django.contrib.auth.urls")),
        path("admin/", admin.site.urls),
    ]
  5. Make the registration/login.html page template:

    templates/registration/login.html - new file
    <!DOCTYPE html>
    <html>
    <body>
        <form method="post">
          {% csrf_token %}
          {{ form }}
          <input type="submit" value="Log In" />
        </form>
      </body>
    </html>
  6. Make the registration/login_status.html page template

    templates/registration/login_status.html - new file
    <div>
      {% if user.is_authenticated %}
      <form action="{% url 'logout' %}?next={{ request.path }}" method="post">
        {% csrf_token %}
        User: {{ user }} - 
        <button type="submit">Log Out</button>
      </form>
      {% else %}
      {{ user }} - <a href="{% url 'login' %}?next={{ request.path }}">login</a>
      {% endif %}
    </div>
    <hr />

Next Steps

That's it for the basic login/logout functionality. You're ready to work on the site or go back to the home page and pick a Boilerplate Task to try out.

Boilerplate Details

~ fin ~