Set up Login System in Django

From TRCCompSci - AQA Computer Science
Revision as of 17:51, 12 April 2019 by Admin (talk | contribs) (Create a templates folder)
Jump to: navigation, search

Update urls.py

You will need to add the following to your urls.py file:

from django.contrib import admin
from django.urls import path, include # might need to add just include
from django.views.generic.base import TemplateView # add this line

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')), # add this line
    path('', TemplateView.as_view(template_name='home.html'), name='home'), # add this line
]

Update settings.py

You should find the templates section of the settings.py file. You will need to set the 'DIRS', and then add the LOGIN_REDIRECT_URL setting:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this bit
        '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',
            ],
        },
    },
]

LOGIN_REDIRECT_URL = '/' # add this line

Create a templates folder

find the 'manage.py' file in your app folder. The templates folder should be in the same location as 'manage.py':

Templates 1.gif

Create a file called base.html in the templates folder, and copy this code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{% block title %}Django Auth Tutorial{% endblock %}</title>
</head>
<body>
  <main>
    {% block content %}
    {% endblock %}
  </main>
</body>
</html>

Create a file in the template folder called home.html, and copy this code:

{% extends 'base.html' %}

{% block title %}Home{% endblock %}

{% block content %}
{% if user.is_authenticated %}
  Hi {{ user.username }}!
  <a href="{% url 'logout' %}">logout</a>
{% else %}
  <p>You are not logged in</p>
  <a href="{% url 'login' %}">login</a>
{% endif %}
{% endblock %}

Create a new folder inside the template folder called registration, and create a new file called login.html, then copy this code:

{% extends 'base.html' %}

{% block title %}Login{% endblock %}

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

Using the login

run the command to start the server, ie:

manage.py runserver


Now visit the ip address specified:

Templates 2.gif

You should be able to click login:

Templates 3.gif

When you login it should take you back to the home page:

Templates 4.gif