Creating a user authentication system is the most required web application. Django, a high-level Python framework, makes it easy to create a login and register system. In this tutorial, we'll guide you to creating a simple login and register system in Django.
Prerequisites
- Python installed on your system
- Django installed (pip install django)
Settings Up the Project
1. Create a Django Project
django-admin startproject auth
cd auth
python manage.py startapp accounts
2. Add the accounts App to INSTALLED_APPS
Open auth/settings.py and add accounts
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
3. Configure URLs
Add a new urls.py file in the accounts app and include it in the projects urls.py
from django.urls import path
from .import views
urlpatterns = [
path('login', views.CustomLoginView.as_view(), name="login"),
path('register', views.UserRegisterView.as_view(), name="register"),
path('logout', views.logout, name='logout'),
]
4. Add Forms for Login and register
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
# user register form
class CustomUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = [
"first_name",
"last_name",
"username",
"email",
"password1",
"password2",
]
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
# Login form
class CustomLoginForm(AuthenticationForm):
username = forms.CharField(
widget=forms.TextInput(
attrs={"class": "form-control", "placeholder": "Username"}
)
)
password = forms.CharField(
widget=forms.PasswordInput(
attrs={"class": "form-control", "placeholder": "Password"}
)
)
captcha = ReCaptchaField(
label = ''
)
Creating the Views
In accounts/views.py, define views for login, register, and logout.
Login View
from django.shortcuts import render
from .forms import CustomUserCreationForm, CustomLoginForm
from django.urls import reverse_lazy,reverse
from django.contrib.auth import logout as auth_logout
class CustomLoginView(LoginView):
form_class = CustomLoginForm
template_name = 'account/login.html'
success_url = reverse_lazy('home')
def get_success_url(self):
return self.request.GET.get('next') or self.success_url
def dispatch(self, request, *args, **kwargs):
if(self.request.user.is_authenticated):
return redirect('home')
return super().dispatch(request, *args, **kwargs)
Register View
from django.shortcuts import render
from .forms import CustomUserCreationForm
from django.shortcuts import redirect
class UserRegisterView(CreateView):
form_class = CustomUserCreationForm
template_name = "account/register.html"
success_url = reverse_lazy('home')
def form_valid(self, form):
response = super().form_valid(form)
user = form.save()
login(self.request, user)
return redirect(self.success_url)
def dispatch(self, request, *args, **kwargs):
if(self.request.user.is_authenticated):
return redirect('home')
return super().dispatch(request, *args, **kwargs)
Logout View
from django.shortcuts import redirect
from django.contrib.auth import logout as auth_logout
def logout(request):
auth_logout(request)
return redirect('/')
Creating Templates
In the accounts app, create a templates/accounts directory and add the following templates:
Register Templates:register.html
<html lang="en">
<head>
<title>Register</title>
</head>
<body>
<section class="auth-area">
<div class="container">
<div class="row">
<div class="col-xl-5 col-lg-5">
<div class="auth-card">
<div class="d-flex align-items-center gap-1 mb-4">
<h1 class="f-18 mb-0 text-capitalize">Register</h1>
</div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="d-flex align-items-center justify-content-between flex-wrap">
<button type="submit" class="site-button-secondry btn-effect">Register</button>
<div class="mt-3 text-center">Have an account <a href="{% url 'login' %}" class="text-secondary">login here</a></div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="background-overlay"></div>
</section>
</body>
</html>
Login Templates: login.html
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
<section class="auth-area ">
<div class="container">
<div class="row">
<div class="col-xl-5 col-lg-5">
<div class="auth-card">
<div class="d-flex align-items-center gap-1 mb-4">
<img src="{% static 'images/devify-footer-logo.png' %}" class="auth-logo" alt="devify logo" loading="lazy"/>
<h1 class="f-18 mb-0 text-capitalize">Login into Devify blog</h1>
</div>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="d-flex align-items-center justify-content-between flex-wrap">
<button type="submit" class="site-button-secondry btn-effect">Log In</button>
</div>
<div class="mt-3 text-center">You don't have account <a href="{% url 'register' %}" class="text-secondary">register here</a></div>
</form>
{% if form.non_field_errors %}
<div class="alert alert-danger">
{{ form.non_field_errors }}
</div>
{% endif %}
</div>
</div>
</div>
</div>
<div class="background-overlay"></div>
</section>
<style>
.errorlist {
color: red;
}
</style>
</body>
</html>
Conclusion
This tutorial covered the basics of creating a user authentication system in Django, including registration and login forms. You can further customize these forms and views to suit your application's requirements, such as adding additional fields or integrating third-party authentication like Google or Facebook.
Have questions or need further assistance? Leave a comment below! 😊
Login to leave a comment.