Django login and Logout code :-
Step 1:-
write code for forms.py file:-
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django import forms
class EditProfileForm(UserChangeForm):
password = forms.CharField(label="", widget=forms.TextInput(attrs={'type':'hidden'}))
class Meta:
model = User
#excludes private information from User
fields = ('username', 'first_name', 'last_name', 'email','password',)
class SignUpForm(UserCreationForm):
email = forms.EmailField(label="", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Email Address'}), )
first_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'First Name'}))
last_name = forms.CharField(label="", max_length=100, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}))
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['username'].widget.attrs['placeholder'] = 'User Name'
self.fields['username'].label = ''
self.fields['username'].help_text = '<span class="form-text text-muted"><small>Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</small></span>'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['placeholder'] = 'Password'
self.fields['password1'].label = ''
self.fields['password1'].help_text = '<ul class="form-text text-muted small"><li>Your password can\'t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can\'t be a commonly used password.</li><li>Your password can\'t be entirely numeric.</li></ul>'
self.fields['password2'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password'
self.fields['password2'].label = ''
self.fields['password2'].help_text = '<span class="form-text text-muted"><small>Enter the same password as before, for verification.</small></span>'
step 2:- write code for views.py file :-
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm
from django.contrib import messages
from .forms import SignUpForm, EditProfileForm
# Create your views here.
def home(request):
return render(request, 'authenticate/home.html', {})
def login_user (request):
if request.method == 'POST': #if someone fills out form , Post it
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:# if user exist
login(request, user)
messages.success(request,('Youre logged in'))
return redirect('home') #routes to 'home' on successful login
else:
messages.success(request,('Error logging in'))
return redirect('login') #re routes to login page upon unsucessful login
else:
return render(request, 'authenticate/login.html', {})
def logout_user(request):
logout(request)
messages.success(request,('Youre now logged out'))
return redirect('home')
def register_user(request):
if request.method =='POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request,user)
messages.success(request, ('Youre now registered'))
return redirect('home')
else:
form = SignUpForm()
context = {'form': form}
return render(request, 'authenticate/register.html', context)
def edit_profile(request):
if request.method =='POST':
form = EditProfileForm(request.POST, instance= request.user)
if form.is_valid():
form.save()
messages.success(request, ('You have edited your profile'))
return redirect('home')
else: #passes in user information
form = EditProfileForm(instance= request.user)
context = {'form': form}
return render(request, 'authenticate/edit_profile.html', context)
#return render(request, 'authenticate/edit_profile.html',{})
def change_password(request):
if request.method =='POST':
form = PasswordChangeForm(data=request.POST, user= request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
messages.success(request, ('You have edited your password'))
return redirect('home')
else: #passes in user information
form = PasswordChangeForm(user= request.user)
context = {'form': form}
return render(request, 'authenticate/change_password.html', context)
step 3:- urls.py file code :-
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout, update_session_auth_hash
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, PasswordChangeForm
from django.contrib import messages
from .forms import SignUpForm, EditProfileForm
# Create your views here.
def home(request):
return render(request, 'authenticate/home.html', {})
def login_user (request):
if request.method == 'POST': #if someone fills out form , Post it
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:# if user exist
login(request, user)
messages.success(request,('Youre logged in'))
return redirect('home') #routes to 'home' on successful login
else:
messages.success(request,('Error logging in'))
return redirect('login') #re routes to login page upon unsucessful login
else:
return render(request, 'authenticate/login.html', {})
def logout_user(request):
logout(request)
messages.success(request,('Youre now logged out'))
return redirect('home')
def register_user(request):
if request.method =='POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request,user)
messages.success(request, ('Youre now registered'))
return redirect('home')
else:
form = SignUpForm()
context = {'form': form}
return render(request, 'authenticate/register.html', context)
def edit_profile(request):
if request.method =='POST':
form = EditProfileForm(request.POST, instance= request.user)
if form.is_valid():
form.save()
messages.success(request, ('You have edited your profile'))
return redirect('home')
else: #passes in user information
form = EditProfileForm(instance= request.user)
context = {'form': form}
return render(request, 'authenticate/edit_profile.html', context)
#return render(request, 'authenticate/edit_profile.html',{})
def change_password(request):
if request.method =='POST':
form = PasswordChangeForm(data=request.POST, user= request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
messages.success(request, ('You have edited your password'))
return redirect('home')
else: #passes in user information
form = PasswordChangeForm(user= request.user)
context = {'form': form}
return render(request, 'authenticate/change_password.html', context)
templates folders :-
login.html file code :-
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name ="home"),
path('login/', views.login_user, name ='login'),
path('logout/', views.logout_user, name='logout'),
path('register/', views.register_user, name='register'),
path('edit_profile/', views.edit_profile, name='edit_profile'),
path('change_password/', views.change_password, name='change_password'),
]
register.html file code :-
{% extends 'authenticate/base.html' %}
{% block content %}
<h2 class ="text-center"> Register </h2>
<div class = "col-md-6 offset-md-3">
<form method="POST" action="{% url 'register' %}">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-danger alart-dismissable" role ="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{% for field in form%}
{% if field.errors%}
{{field.errors}}
{% endif%}
{% endfor %}
</div>
{% endif %}
{{ form.as_p }}
<input type="submit" value="Register" class=" btn btn-secondary">
</form>
</div>
{% endblock %}
home.html file code :-
{% extends 'authenticate/base.html' %}
{% block content %}
<h1> Home page</h1>
{% if user.is_authenticated %}
<p>Name: {{user.first_name}} {{ user.last_name}}</p>
<p>Username: {{user.username}}</p>
<p>Email: {{user.email}}</p>
{% endif %}
{% endblock %}
write code for edit_profile.html file :-
{% extends 'authenticate/base.html' %}
{% block content %}
<h2 class ="text-center"> Edit Profile </h2>
<form method="POST" action="{% url 'edit_profile' %}">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-danger alart-dismissable" role ="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{% for field in form %}
{% if field.errors %}
{{ field.errors }}
{% endif%}
{% endfor %}
</div>
{% endif %}
{{ form.as_p }}
<input type="submit" value="Edit Profile" class=" btn btn-secondary">
<p><small><a href="{% url 'change_password'%}">Click here</a> to change your password</small></p>
</form>
{% endblock %}
write code for change_password.html file:-
{% extends 'authenticate/base.html' %}
{% block content %}
<h2 class ="text-center"> Change Password </h2>
<form method="POST" action="{% url 'change_password' %}">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-danger alart-dismissable" role ="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{% for field in form %}
{% if field.errors %}
{{ field.errors }}
{% endif%}
{% endfor %}
</div>
{% endif %}
{{ form.as_p }}
{# button #}
<input type="submit" value="Change Password" class=" btn btn-secondary">
</form>
{% endblock %}
write code for base.html file:-
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{% url 'home' %}">Miami Ascension</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
{# Will know if user is logged in or not#}
{% if user.is_authenticated %}
<li class="nav-item active">
<a class="nav-link" href="{% url 'logout' %}">Logout</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{% url 'edit_profile' %}">Edit Profile</a>
</li>
{% else %}
<li class="nav-item active">
<a class="nav-link" href="{% url 'login' %}">Login</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% endif%}
</ul>
</div>
</nav>
<br/>
<div class ="container">
{% if messages %}
{% for message in messages %}
<div class="alert alert-danger alart-dismissable" role ="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{{ message }}
</div>
{% endfor%}
{% endif %}
{% block content %}
{% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Sign up here with your email
ConversionConversion EmoticonEmoticon