Building an app in Django: the login

I’ve spoken in depth about getting Django ready to use in this article, so I’m not going to go through the general setup commands in too much detail. Suffice to say, once you’ve got your server up and running, you’ll want to configure the firewall and start your Django app.

    1  sudo apt install ufw
    2  ufw allow ssh
    3  ufw allow 8000
    4  ufw allow www
    5  ufw allow https
    6  ufw enable
    9  cd var/www/DjangoApp/
   11  python3 startapp appname

Now, to create your login form, we’re going to setup our We’re going to use the out of the box django auth urls, and those urls are going to sit under /account. So we might have for example. We don’t need to configure those URL’s explicitly, rather, we declare simply /accounts. Then we put our HTML page under: Templates > registration > login.html.

from django.contrib import admin
from django.urls import path
from appname import views
from django.urls import path, include # new

urlpatterns = [ 
    path('', views.home, name='home'),
    path('dash', views.dash, name='dash'),
    path('accounts/', include('django.contrib.auth.urls')),

Next, as part of the standard setup process, we need to define where our static files live; where our templates are stored and we need to define our redirect URL once someone has logged in.

STATIC_URL = '/static/'
    os.path.join(BASE_DIR, 'static'),]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates/'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

Finally, we create our login page, which has a standard login form {{ form.as_p }}. Note that, if you want to include your own CSS in the page, you’ll need to reference it like is shown at the top of the code block below.

{% load static %}      
<link href="{% static "assets/dist/css/bootstrap.css"%}" rel="stylesheet">

 <form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>

One thought on “Building an app in Django: the login

Comments are closed.