Django signup and login and Logout Code step by step guidance :-
Step 1:-
Models.py file code of your app folder:-
from django.db import models
Step 2:- create forms.py file in your app folder
forms.py file code :-
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ["username", "email", "password1", "password2"]
Step 3:- urls.py file of app folder:-
from django.urls import path
from .import views
urlpatterns=[
path('',views.index,name='index'),
path('home/',views.home,name='home'),
path('homepage/',views.homepage,name='homepage'),
path("register", views.register_request, name="register"),
path("login", views.login_request, name="login"),
path("logout", views.logout_request, name= "logout"),
]
Step 4:- views.py file of app folder:-
from urllib import request
from django.shortcuts import render,redirect
from .forms import NewUserForm
from django.contrib.auth import login, authenticate,logout #add this
from django.contrib import messages
from django.contrib.auth.forms import AuthenticationForm
def homepage(request):
return render(request, "homepage.html")
def home(request):
serviceData=”Registration successful”
data={'serviceData':serviceData
}
return render(request,"home.html",data)
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as {username}.")
return redirect("homepage")
else:
messages.error(request,"Invalid username or password.")
else:
messages.error(request,"Invalid username or password.")
form = AuthenticationForm()
return render(request, 'login.html', context={"login_form":form})
def register_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, "Registration successful." )
return redirect("home")
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm()
return render (request, 'register.html', context={"register_form":form})
def logout_request(request):
logout(request)
messages.info(request, "You have successfully logged out.")
return redirect("homepage")
Step 5:- Create templates folder and write code for homepage.html :-
<!--Navbar-->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="False" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav mr-auto">
{% 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="#">Welcome, {{user.username}}</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Login</a>
</li>
{% endif %}
</ul>
</div>
</nav>
Register.html file code:-
<div class="container py-5">
<h1>Register</h1>
<form method="POST">
{% csrf_token %}
{{ register_form }}
<button class="btn btn-primary" type="submit">Register</button>
</form>
<p class="text-center">If you already have an account, <a href="{% url 'login' %}">login</a> instead.</p>
</div>
Login.html file code:-
<!--Login-->
<div class="container py-5">
<h1>Login</h1>
<form method="POST">
{% csrf_token %}
{{ login_form}}
<button class="btn btn-primary" type="submit">Login</button>
</form>
<p class="text-center">Don't have an account? <a href="{% url 'register' %}">Create an account</a>.</p>
</div>
home.html file code:-
<h1 class="myclass">hello world how are you
{{data}}
</h1>
Now to run it use following command
py manage.py runserver in your command prompt as shown below
http://127.0.0.1:8000/hello/register
and you will see output
http://127.0.0.1:8000/hello/login
Sign up here with your email
ConversionConversion EmoticonEmoticon