Difference between revisions of "Set up Login System in Django"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Update settings.py)
(Initial Setup)
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Update urls.py=
+
=Initial Setup=
 +
Before you attempt this you should create a superuser in django, otherwise you won't have a username & password to test.
  
You will need to add the following to your urls.py file:
+
Run the DjangoAdmin program, choose the 'Manage' option and then 'createsuperuser'.
 +
 
 +
==Project URL's==
 +
If you have created a django project by running the 'startproject' option of django-admin, it will create a folder which contains a file called 'urls.py'. This is the file used to define the URL's accepted by your web app. For a login/logout system we can use the built in django methods, and will mainly need to add code into this file.
 +
 
 +
Open the 'urls.py', you will need to import the following at the top of the page:
  
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
from django.contrib import admin
+
from django.contrib.auth import views as auth_views
from django.urls import path, include # might need to add just include
+
</syntaxhighlight>
from django.views.generic.base import TemplateView # add this line
 
  
urlpatterns = [
+
Next, you will see a section which defines 'urlpatterns', we need to add some additional entries into this:
    path('admin/', admin.site.urls),
+
 
    path('accounts/', include('django.contrib.auth.urls')), # add this line
+
<syntaxhighlight lang=python>
    path('', TemplateView.as_view(template_name='home.html'), name='home'), # add this line
+
path('login/', auth_views.LoginView.as_view(), name='login'),
]
+
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
 +
</syntaxhighlight>
 +
 
 +
If you don't have a root path defined, look at the previous tutorial: [[Creating the Home page in Django]].
 +
 
 +
==Settings==
 +
 
 +
Now in the project folder you should see a file called 'settings.py', we need to add this line:
 +
<syntaxhighlight lang=python>
 +
LOGIN_URL = 'login'
 +
LOGIN_REDIRECT_URL = '/'
 +
LOGOUT_REDIRECT_URL = '/'
 
</syntaxhighlight>
 
</syntaxhighlight>
=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:
+
=User app=
 +
 
 +
Create a new app in your project called 'users', then in this new folder edit the 'apps.py' file, you should see something like this:
  
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
TEMPLATES = [
+
from django.apps import AppConfig
    {
 
        '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
+
class UsersConfig(AppConfig):
LOGOUT_REDIRECT_URL = '/' # add this line
+
    name = 'users'
 
</syntaxhighlight>
 
</syntaxhighlight>
  
=Create a templates folder=
+
Copy the name of the class, the example above is called UsersConfig. Now goto the 'settings.py' file and find the installed apps definition:
  
find the 'manage.py' file in your app folder. The templates folder should be in the same location as 'manage.py':
+
<syntaxhighlight lang=python>
 +
INSTALLED_APPS = [
 +
    'django.contrib.admin',
 +
    'django.contrib.auth',
 +
    'django.contrib.contenttypes',
 +
    'django.contrib.sessions',
 +
    'django.contrib.messages',
 +
    'django.contrib.staticfiles',
  
[[File:Templates 1.gif]]
+
]
 +
</syntaxhighlight>
  
Create a file called base.html in the templates folder, and copy this code:
+
Add a new entry at the start of this list for your app:
  
<syntaxhighlight lang=html>
+
<syntaxhighlight lang=python>
<!DOCTYPE html>
+
INSTALLED_APPS = [
<html>
+
    'users.apps.UsersConfig',
<head>
+
    'django.contrib.admin',
  <meta charset="utf-8">
+
    'django.contrib.auth',
  <title>{% block title %}Django Auth Tutorial{% endblock %}</title>
+
    'django.contrib.contenttypes',
</head>
+
     'django.contrib.sessions',
<body>
+
     'django.contrib.messages',
  <main>
+
    'django.contrib.staticfiles',
     {% block content %}
+
]
     {% endblock %}
 
  </main>
 
</body>
 
</html>
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Create a file in the template folder called home.html, and copy this code:
+
=User Templates=
 +
In the folder for your users app, create a folder called templates. Inside this create a folder called users:
  
<syntaxhighlight lang=html>
+
[[File:Template folder.png]]
{% extends 'base.html' %}
 
  
{% block title %}Home{% endblock %}
+
Now in this folder add a new item, and select 'HTML' and call it 'login.html':
  
{% block content %}
+
[[File:New html.png]]
{% 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 %}
 
</syntaxhighlight>
 
  
Create a new folder inside the template folder called registration, and create a new file called login.html, then copy this code:
+
Now replace the whole html code with this (the previous tutorial created 'base.html'):
  
 
<syntaxhighlight lang=html>
 
<syntaxhighlight lang=html>
{% extends 'base.html' %}
+
{% extends "MyApp/base.html" %}
 
 
{% block title %}Login{% endblock %}
 
  
 
{% block content %}
 
{% block content %}
Line 98: Line 94:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
=Using the login=
+
Now back in 'urls.py', find:
run the command to start the server, ie:
+
 
 +
<syntaxhighlight lang=python>
 +
path('login/', auth_views.LoginView.as_view(), name='login'),
 +
</syntaxhighlight>
  
manage.py runserver
+
Now inside the round brackets after '.as_view' enter:
  
 +
template_name='users/login.html'
  
Now visit the ip address specified:
+
So it should be:
  
[[File:Templates 2.gif]]
+
<syntaxhighlight lang=python>
 +
path('login/', auth_views.LoginView.as_view(template_name='users/login.html' ), name='login'),
 +
</syntaxhighlight>
  
You should be able to click login:
+
=Edit the Base.HTML=
  
[[File:Templates 3.gif]]
+
In the 'base.html' file find the following section:
  
When you login it should take you back to the home page:
+
<syntaxhighlight lang=html>
 +
    <ul class="nav navbar-nav navbar-right">
 +
      <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
 +
      <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
 +
    </ul>
 +
</syntaxhighlight>
  
[[File:Templates 4.gif]]
+
Change this section to this:
 +
<syntaxhighlight lang=html>
 +
    <ul class="nav navbar-nav navbar-right">
 +
      {% if user.is_authenticated %}
 +
        <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> LogOut</a></li>
 +
      {% else %}
 +
        <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
 +
        <li><a href="{% url 'login' %}"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
 +
      {% endif %}
 +
    </ul>
 +
</syntaxhighlight>

Latest revision as of 07:41, 11 September 2019

Initial Setup

Before you attempt this you should create a superuser in django, otherwise you won't have a username & password to test.

Run the DjangoAdmin program, choose the 'Manage' option and then 'createsuperuser'.

Project URL's

If you have created a django project by running the 'startproject' option of django-admin, it will create a folder which contains a file called 'urls.py'. This is the file used to define the URL's accepted by your web app. For a login/logout system we can use the built in django methods, and will mainly need to add code into this file.

Open the 'urls.py', you will need to import the following at the top of the page:

from django.contrib.auth import views as auth_views

Next, you will see a section which defines 'urlpatterns', we need to add some additional entries into this:

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

If you don't have a root path defined, look at the previous tutorial: Creating the Home page in Django.

Settings

Now in the project folder you should see a file called 'settings.py', we need to add this line:

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

User app

Create a new app in your project called 'users', then in this new folder edit the 'apps.py' file, you should see something like this:

from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'

Copy the name of the class, the example above is called UsersConfig. Now goto the 'settings.py' file and find the installed apps definition:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

]

Add a new entry at the start of this list for your app:

INSTALLED_APPS = [
    'users.apps.UsersConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

User Templates

In the folder for your users app, create a folder called templates. Inside this create a folder called users:

Template folder.png

Now in this folder add a new item, and select 'HTML' and call it 'login.html':

New html.png

Now replace the whole html code with this (the previous tutorial created 'base.html'):

{% extends "MyApp/base.html" %}

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

Now back in 'urls.py', find:

path('login/', auth_views.LoginView.as_view(), name='login'),

Now inside the round brackets after '.as_view' enter:

template_name='users/login.html' 

So it should be:

path('login/', auth_views.LoginView.as_view(template_name='users/login.html' ), name='login'),

Edit the Base.HTML

In the 'base.html' file find the following section:

    <ul class="nav navbar-nav navbar-right">
      <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
      <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
    </ul>

Change this section to this:

     <ul class="nav navbar-nav navbar-right">
       {% if user.is_authenticated %}
         <li><a href="{% url 'logout' %}"><span class="glyphicon glyphicon-log-out"></span> LogOut</a></li>
       {% else %}
         <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
         <li><a href="{% url 'login' %}"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
       {% endif %}
     </ul>