Skip to content

Instantly share code, notes, and snippets.

@b-mackey
Last active December 10, 2021 19:34
Show Gist options
  • Save b-mackey/7569a90397fcfb98ea028db02663de74 to your computer and use it in GitHub Desktop.
Save b-mackey/7569a90397fcfb98ea028db02663de74 to your computer and use it in GitHub Desktop.
Django Auth Setup

Using Django Auth for Site Authentication

Used to allow multiple users to register for a given application

Setup Accounts skeleton

  • Create a new app called 'accounts'
python manage.py startapp accounts
  • Set up templates directory under 'accounts', add login.html & signup.html pages

  • Add 'accounts' under INSTALLED_APPS in settings.py

  • Create forms.py and urls.py files for 'accounts'

Populate HTML Templates

Complete login.html and signup.html templates

{% extends 'base.html' %}
{% load bootstrap3 %}
{% block title %}
Login / Signup
{% endblock %}
{% block content %}

    <div class="container">
        <h1>Login / Signup</h1>
        <form method="POST">
            {% csrf_token %}
            {% bootstrap_form form %}
            <input type="submit" value="Login" class="btn btn-primary">
        </form>
    </div>

{% endblock %}

Create User Model, View and URLs

Define User Model in models.py

from django.contrib.auth.models import User, PermissionsMixin


class SiteUser(User, PermissionsMixin):

    def __str__(self):
        return "@{}".format(self.username)

Create a Form for User Signup

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

# UserCreationForm has built-in password validation
# https://docs.djangoproject.com/en/2.0/topics/auth/default/

class UserCreateForm(UserCreationForm):

    class Meta:
        fields = ('username', 'email', 'password1', 'password2')
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super(UserCreateForm, self).__init__(*args, **kwargs)
        self.fields['username'].label = 'Display Name'
        self.fields['email'].label = 'Email Address'
        self.fields['password1'].label = 'Password'
        self.fields['password2'].label = 'Verify Password'

Create a View for Signup

from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView

from . import forms

# LoginView and LogoutView are provided by django.contrib.auth
# https://docs.djangoproject.com/en/2.0/topics/auth/default/

class SignUp(CreateView):
    form_class = forms.UserCreateForm
    success_url = reverse_lazy('login')
    template_name = 'accounts/signup.html'

Add URLs for Users

In the main project's urls.py file

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

from . import views

urlpatterns = [
    path('admin/', admin.site.urls),

    path('accounts/', include('accounts.urls', namespace='accounts')),
    path('accounts/', include('django.contrib.auth.urls')),
]

In the app's urls.py file

from django.contrib.auth import views as auth_views
from django.urls import path

from . import views

app_name = 'accounts'

urlpatterns = [

    # LoginView and LogoutView are provided by django.contrib.auth
    # https://docs.djangoproject.com/en/2.0/topics/auth/default/

    path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),

    # Create URL for signup page

    path('signup/', views.SignUp.as_view(), name='signup'),
]

Use User in other models

from django.contrib.auth import get_user_model

User = get_user_model()

class UserProfile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment