Set up Login System in Django
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':
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 }}!
{% 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 %}