A Django Blog In VS Code — Authentications, Login & Logout

How To Create A Blog in VS Code — Part V— DjangoSeries Episode # 08

J3
Jungletronics
5 min readFeb 8, 2022

--

Hi, in this post we’re going to be learning how to create an authentication system for our Django application so that users can log in log out.

Let’s go ahead and get started!

00#Step — This is a continuation of this post;

In the previous episode we saw how to create this registration page where users could create new accounts but they’re not able to log:

Our registration page created at the previous #DjangoSeries episode #07.

Admin dashboard is only for users with admin access privilege.

While the admin site is very useful, remember that its primary audience is administrators, not end-users. It’s a back-end interface that offers far greater functionality than what end-users should have access to. It’s also very plain-looking.

Your end-users will expect to use forms that are styled like the rest of your site. You may also want to customize the position of a form within a page, exclude some fields, and make other UX customizations. For these reasons, you still need to learn how to build forms into your web app’s front end in later episodes.

By default our new users aren’t going to have to the admin site so we need to have a login page for them on the front end.

Let’s get started by using Django default login views.

01#Step — GoTo django_project/urls.py and add:

from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users_hub import views as user_views
urlpatterns = [path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name="users_hub/login.html"), name='login'),
path('logout/', auth_views.LogoutView.as_view(
template_name="users_hub/logout.html"), name='logout'),
path('', include('blog.urls')),

02#Step — If you try to access /login page by running the server you will receive this error:

python manage.py runserver
there is no users_hub/login.html :/ Oops!...I Did It Again :)

It will try to upload a template at users_hub/login.html, which we didn’t create yet…

03#Step —Create a login.html template inside:

users_hub/templates/users_hub/login.html
users_hub/login.html

04#Step — Create a users_hub/logout.html

05#Step — Create a users_hub/profile.html

06#Step — GoTo django_project/Settings.py and at the very end, add:

....# Crisp configCRISPY_TEMPLATE_PACK = 'bootstrap4'# Redirecting to home
LOGIN_REDIRECT_URL = 'blog-home'
ACCOUNT_LOGOUT_REDIRECT_URL = 'blog-home'
LOGIN_URL = 'login'

07#Step — Modify users_hub/views.py to:

from django.shortcuts import render, redirect
from django.contrib import messages
from users_hub.forms import UserRegisterForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Hi {username}! Your account has been created! Now login!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users_hub/register.html', {'form': form})
@login_required
def profile(request):
return render(request, 'users_hub/profile.html')

After the user have successfully registered it would make a lot more sense right here to redirect them to the login page, right?

08#Step — Now Let’s try to register userTest3:

And there you have it! 👍

09#Step — GoTo django_project\blog\templates\blog\base.html

Open up our base template that contains the navigation and then put in a conditional that checks whether the user is logged in or logged out:

   <li class="nav-item">
<a class="nav-link active" aria-current="page" href="{% url 'blog-home' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'about-page' %}">About</a> </li>
{% if user.is_authenticated %}

<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Logout</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'profile' %}">Profile</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% endif %}
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'profile' %}">Hi,{{ user }}!</a>
</li>
{% endif %}

10#Step — Access login route:

11#Step — Create a users_hub/register.html

12#Step — Modify your blog/base.html template:

Notice each of the modifications in the method links 👆

13#Step — Here is your final django_project/urls.html template:

That’s all Folks!

In the next #DjangoSeries Episode we will continue to customize registration in Django with Upload Profile Image.

See you around. Bye!

👉 git

Related Posts

00#Episode — DjangoSerie — Django Intro — How To Build your First App in Python Django Framework — DjangoSeries

01#Episode — DjangoSerie — Django MTV In VS Code — How To Install Django Inside Virtual VS Code

02#Episode — DjangoSerie — Can You Solve This in Python? — Here is A Basic Python Question!

03#Episode — DjangoSerie — JUNGLE-DJANGO Webpage! This Is My New Django Netflix Clone Page!

04#Episode — DjangoSerie — A Django Blog In VS Code — Quick Start!Part_I

05#Episode — DjangoSerie — A Django Blog In VS Code — Database, Migrations & Queries — Part_II

06#Episode — DjangoSerie — A Django Blog In VS Code — Bootstrap, Tailwind CSS — Part_III

07#Episode — DjangoSerie — A Django Blog In VS Code — Forms & Validations — Part_IV

08#Episode — DjangoSerie — A Django Blog In VS Code — Login & Logout — Part_V (this one :)

09#Episode — DjangoSerie — A Django Blog In VS Code — Upload Profile Picture — Part_VI

10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII

11#Episode — DjangoSerie — A Django Blog In VS Code — Class-Based-View & CRUD — Part_VIII

12#Episode — DjangoSerie — A Django Blog In VS Code — Posts Pagination & Quick DB Population — Part_IX

13#Episode — DjangoSerie — A Django Blog In VS Code — Self-Service Django Password Reset — Part_X

14#Episode — DjangoSerie — A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Productio — Part_XI (this last one…whew!)

Credits & References

Python Django Tutorial: Full-Featured Web App by Corey Schafer

HowTo Run this Tutorial - From the Scratch - In your Machine:)Annotations: Quick Start - video #TakeTheFirstStepToLearnDjango0 - Download DJG_<previous>/Django_project from my git repo;
1 - On your desktop, create a dir and named it as Tutorial_#;
2 - Inside this paste the previous Django_project file;
3 - GoTo vscode Terminal (command prompt) and ...
4 - Run this quick_script
(copy/paste inside you terminal and hit enter and wait until
Pillow is up and running...):
python -m venv djangoEnv
djangoEnv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install django
python -m django --version
pip install django-crispy-forms
pip install Pillow
5- GoTo Step#01 of this tutorial.And you are good to go!

--

--

J3
Jungletronics

😎 Gilberto Oliveira Jr | 🖥️ Computer Engineer | 🐍 Python | 🧩 C | 💎 Rails | 🤖 AI & IoT | ✍️