Source Code Python Django user sign up, login, logout, reset password

preview_player
Показать описание
Scripting for user authentication in Sign Up, Registration and reactivation by email to user created, user Login, Logout and Reset Password by sending link reset.
Рекомендации по теме
Комментарии
Автор

Here I put all source code about Sign Up, Login, Logout, Reset Password

pythondjangowebapplication
Автор

Index.html

{% extends 'base.html' %}

{% block content %}
<strong>O</strong>ffice <strong>S</strong>ystem <strong>J</strong>ava</h1>
<p>This Application developed using Python Django Framework <em>connected to Oracle Database 12C</em>!</p>
<h2>Dynamic content</h2>
<p>The Application has the following record counts:</p>

{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}

<ul>
<li><strong>Order records:</strong> {{ num_order }}</li>
<li><strong>Order Item records:</strong> {{ num_orderitem }}</li>
<li><strong>User Login records:</strong> {{ num_user_log }}</li>
</ul>

{% endblock %}

pythondjangowebapplication
Автор

Scripting below only applied in Oracle Database

You may change this scripts when you connect to MySQL, SQL Server, PostGreSQL or other Database

pythondjangowebapplication
Автор

password_reset_complete.html

{% extends "base.html" %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6 col-lg-5">
<div class="alert alert-success text-center shadow">
✅ Your password has been successfully reset!
</div>
<div class="text-center mt-3">
<a href="{% url 'login' %}" class="btn btn-primary">Login with New Password</a>
</div>
</div>
</div>
</div>
{% endblock %}

pythondjangowebapplication
Автор

models.py

class Loginhistory(models.Model):
id =
# userid = models.FloatField(blank=True, null=True)
# ip_address = models.CharField(max_length=50, blank=True, null=True)
# login_time = models.DateField(blank=True, null=True)

user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='USERID')
ip_address = models.GenericIPAddressField(null=True, blank=True)
login_time =
action = models.CharField(max_length=10, choices=[('login', 'Login'), ('logout', 'Logout')])

class Meta:
managed = False
db_table = 'loginhistory'

def __str__(self):
return f"{self.user.username} - {self.ip_address} - {self.login_time}"

pythondjangowebapplication
Автор

settings.py

"""
Django settings for tmol project.

Generated by 'django-admin startproject' using Django 4.0.5.

For more information on this file, see

For the full list of settings and their values, see
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR =


# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY =

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'orderapp.apps.OrderappConfig',
'widget_tweaks',
]


MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'tmol.urls'

SESSION_ENGINE =

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]

WSGI_APPLICATION = 'tmol.wsgi.application'


# Database

#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
#}

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'orclpy',
# 'NAME': 'orcl12c',
'USER': 'tmol',
'PASSWORD': 'tmol',
'HOST': 'desktop-uslpa88',
# 'USER': 'pydjango',
# 'PASSWORD': 'pydjango',
# 'HOST': 'WIN-QNVEVJ6RB1L',
'PORT': '1521',
}
}

# Password validation

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)

STATIC_URL = 'static/'

# Default primary key field type

DEFAULT_AUTO_FIELD =

LOGIN_URL = 'login' # name of your login view
LOGIN_REDIRECT_URL = 'index' # or wherever you want after login
LOGOUT_REDIRECT_URL = 'login'


EMAIL_BACKEND =
EMAIL_HOST = 'mail.kuwad.com' # or another provider
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = 'Tmol930251!@#$'

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

from django.contrib.messages import constants as messages

MESSAGE_TAGS = {
messages.DEBUG: 'secondary',
messages.INFO: 'info',
messages.SUCCESS: 'success',
messages.WARNING: 'warning',
messages.ERROR: 'danger',
}

pythondjangowebapplication
Автор

password_reset_confirm.html

{% extends "base.html" %}
{% block content %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6 col-lg-5">
<div class="card shadow">
<div class="card-body">
<h4 class="text-center mb-4">🔐 Set a New Password</h4>
{% if validlink %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<div class="d-grid mt-3">
<button type="submit" class="btn btn-success">Change Password</button>
</div>
</form>
{% else %}
<div class="alert alert-danger text-center">
The password reset link is invalid or has expired.
</div>
{% endif %}
</div>
</div>
</div>
</div>
</div>
{% endblock %}

pythondjangowebapplication
Автор

urls.py

from django.urls import path
from . import views
from .views import get_product_price, order_list, order_items, create_order, get_product_price1, get_refer_dtl, get_refer_dtl_by_group, get_refer_dtl_by_group1, login_view

from django.urls import include
from django.contrib.auth import views as auth_views

urlpatterns = [
# path('accounts/login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('accounts/login/', login_view, name='login'),
# path('login/', views.login_view, name='login'),
path('', views.index, name='index'),
path('dashboard/', views.dashboard_view, name='dashboard'),
path('logout/', views.logout_view, name='logout'),
path('register/', views.register_view, name='register'),
path('activate/<uidb64>/<token>/', views.activate_account, name='activate'),

path('accounts/profile/', views.profile_view, name='profile'),

# Password Reset Flow
path('accounts/password_reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset_form.html'), name='password_reset'),
path('accounts/password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'),
path('accounts/reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'),
path('accounts/reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete'),

pythondjangowebapplication
Автор

views.py part 01

from import login_required

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.conf import settings
from django.urls import reverse

def login_view(request):
if
# return redirect('dashboard') # Redirect if already logged in
return redirect('index') # Redirect if already logged in

if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)

if user is not None:
login(request, user)
return redirect('index')
else:
# Check if user exists but is not active
try:
user_check =
if not user_check.is_active:
messages.error(request, "Your account is not activated. Please check your email.")
else:
messages.error(request, "Invalid username or password.")
except User.DoesNotExist:
messages.error(request, "User doesn't exist, please sign up/register !!.")

return render(request, 'accounts/login.html')


def logout_view(request):
logout(request)
return redirect('login')


@login_required
def index(request):
# Generate counts of some of the main objects

num_order = Orders.objects.all().count()

# num_user_log =

latest_logins = (
Loginhistory.objects
.filter(action='login')
.values('user')

)


action='login',
for item in latest_logins]
).count()



context = {

'num_order': num_order,
'num_orderitem': num_orderitem,
'num_user_log': num_user_log,
}

# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context=context)

pythondjangowebapplication
Автор

signals.py

from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.dispatch import receiver
from django.utils.timezone import now

from .models import Loginhistory

@receiver(user_logged_in)
def track_login(sender, request, user, **kwargs):
print("📥 user_logged_in signal received!")
ip =
print(f"User {user.username} logged in from IP: {ip}")
try:
Loginhistory.objects.create(user=user, ip_address=ip, action='login')
except Exception as e:
print(f"❌ Failed to create login history: {e}")

= str(now())


@receiver(user_logged_out)
def track_logout(sender, request, user, **kwargs):
print("📥 user_logged_out signal received!")
ip =
print(f"User {user.username} logged out from IP: {ip}")
try:
Loginhistory.objects.create(user=user, ip_address=ip, action='logout')
except Exception as e:
print(f"❌ Failed to create logout history: {e}")

= str(now())

pythondjangowebapplication
Автор

views.py part 02

from django.contrib.auth.models import User
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes
from django.template.loader import render_to_string
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import send_mail
from django.conf import settings
from django.urls import reverse

def register_view(request):
if
return redirect('dashboard')

if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
confirm = request.POST['confirm']

if password != confirm:
messages.error(request, "Passwords do not match.")
elif
messages.error(request, "Username already taken.")
else:
user = User.objects.create_user(username=username, email=email, password=password, is_active=False)
# login(request, user) # Auto-login after registration
user_creation_success=True

# return redirect('dashboard')

if user_creation_success:
uid =
token =

activation_link = request.build_absolute_uri(
reverse('activate', kwargs={'uidb64': uid, 'token': token})
)

message = render_to_string('emails/activation_email.html', {
'user': user,
'activation_link': activation_link
})

send_mail(
'Activate your account',
message,
settings.DEFAULT_FROM_EMAIL,
[user.email],
fail_silently=False,
html_message=message
)

messages.success(request, "Check your email to activate your account.")
return redirect('login')


return render(request, 'registration/register.html')


from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.utils.http import urlsafe_base64_decode
from django.utils.encoding import force_str
from django.shortcuts import render, redirect

def activate_account(request, uidb64, token):
try:
uid =
user = User.objects.get(pk=uid)
except (TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None

if user is not None and default_token_generator.check_token(user, token):
user.is_active = True
user.save()
return render(request,
else:
return render(request,

pythondjangowebapplication
Автор

admin.py

from django.contrib import admin

# Register your models here.
from django.contrib import admin
from .models import Loginhistory

@admin.register(Loginhistory)
class
list_display = ('user', 'ip_address', 'login_time')

pythondjangowebapplication
Автор

base.html

<!DOCTYPE html>



<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}TMOL{% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<meta charset="UTF-8">
<title>TMOL</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap 5 -->

<!-- Font Awesome for Icons -->

<!-- FullCalendar -->

<!-- Chart.js -->

{% load static %}
<img src="{{ product.image.url }}" alt="{{ product.name }}">


<style>
body { overflow-x: hidden; }
.sidebar {
width: 250px;
height: 100vh;
position: fixed;
top: 0; left: 0;
background: #343a40;
color: white;
transition: width 0.3s;
z-index: 1030;
}
.sidebar.collapsed { width: 80px; }
.sidebar .nav-link { color: white; }
.sidebar .nav-text { display: inline-block; }
.sidebar.collapsed .nav-text { display: none; }
.main-content {
margin-left: 250px;
transition: margin-left 0.3s;
}
.main-content.collapsed { margin-left: 80px; }
.active-link {
background-color: rgba(255, 255, 255, 0.1);
border-left: 3px solid #0d6efd;
}
.navbar-custom {
margin-left: 250px;
transition: margin-left 0.3s;
}
.navbar-custom.collapsed { margin-left: 80px; }
</style>
{% block extra_head %}{% endblock %}
</head>
<body>
<!-- Navbar -->
<nav class="navbar navbar-expand bg-light shadow-sm sticky-top navbar-custom" id="navbar">
<div class="container-fluid">
<button class="btn btn-outline-secondary me-2" id="toggleSidebar">
<i class="fas fa-bars"></i>
</button>
<div class="ms-auto dropdown">
<a class="btn btn-outline-secondary dropdown-toggle" href="#" role="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-user-circle"></i> {{ user.username|default:"Guest" }}
</a>
<ul class="dropdown-menu dropdown-menu-end"
{% if user.is_authenticated %}
<li>
<a class="dropdown-item" href="#">
<i class="fas fa-user me-2"></i>Profile
</a>
</li>
<li>
<a class="dropdown-item" href="{% url 'logout' %}">
<i class="fas fa-sign-in-alt me-2"></i>Logout
</a>
</li>
{% else %}
<li>
<a class="dropdown-item" href="{% url 'login' %}">
<i class="fas fa-sign-in-alt me-2"></i>Login
</a>
</li>
{% endif %}
</ul>
</div>
</div>
<div class="dropdown me-3">
<a class="btn btn-outline-secondary position-relative" href="#" id="notifDropdown" data-bs-toggle="dropdown">
<i class="fas fa-bell"></i>
<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" id="notifCount">0</span>
</a>
<ul class="dropdown-menu dropdown-menu-end" id="notifList">
<li><span class="dropdown-item">No notifications</span></li>
</ul>
</div>


</nav>


<!-- Sidebar -->
<div class="sidebar p-3" id="sidebar">
<h5><i class="fas fa-cube me-2"></i><span
<ul class="nav flex-column">

<!-- Home -->

<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">
<i class="fas fa-home me-2"></i>
<span class="nav-text">Home</span>
</a>
</li>

<!-- Dashboard -->
<li class="nav-item">
<a class="nav-link {% if request.path == '/dashboard/' %}active-link{% endif %}"
href="{% url 'dashboard' %}">
<i class="fas fa-tachometer-alt me-2"></i>
<span
</a>
</li>


<!-- Products -->
<li class="nav-item">
<a class="nav-link d-flex justify-content-between align-items-center
{% if '/products' in request.path %}active{% endif %}"
data-bs-toggle="collapse"
href="#submenu-products"
role="button"
aria-expanded="{% if '/products' in request.path %}true{% else %}false{% endif %}"


<span><i class="fas fa-box-open me-2"></i> Products</span>
<i class="fas fa-chevron-down small"></i>
</a>

<div class="collapse {% if '/products' in request.path %}show{% endif %}" id="submenu-products">
<ul class="nav flex-column ms-3">
<li class="nav-item">
<a class="nav-link {% if request.path == '/products/add/' %}active{% endif %}" href="#">
<i class="fas fa-plus me 2"></i> Add Product
</a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.path == '/products/' %}active-link{% endif %}" href="/products/">
<i class="fas fa-box-open me-2"></i><span class="nav-text">List Products</span>
</a>
</li>
</ul>
</div>
</li>



<!-- Orders -->
<li class="nav-item">
<a class="nav-link d-flex justify-content-between align-items-center
{% if '/orders' in request.path %}active{% endif %}"
data-bs-toggle="collapse"
href="#submenu-orders"
role="button"
aria-expanded="{% if '/orders' in request.path %}true{% else %}false{% endif %}"


<span><i class="fas fa-receipt me-2"></i> Orders</span>
<i class="fas fa-chevron-down small"></i>
</a>

<div class="collapse {% if '/orders' in request.path %}show{% endif %}" id="submenu-orders">
<ul class="nav flex-column ms-3">
<li class="nav-item">
<a class="nav-link {% if request.path == '/orders/add/' %}active{% endif %}" href="#">
<i class="fas fa-plus me-2"></i> Add Orders
</a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.path == '/orders/' %}active-link{% endif %}" href="/orders/">
<i class="fas fa-receipt"></i><span class="nav-text">All Orders</span>
</a>
</li>
</ul>
</div>
</li>


<!-- Projects -->
<li class="nav-item">
<a class="nav-link" href="#">
<i class="fas fa-diagram-project me-2"></i><span
</a>
</li>
</ul>
</div>

<!-- Main Content -->
<div class="main-content p-4" id="main">
{% block content %}{% endblock %}
</div>

<!-- Scripts -->
<script>
const toggleBtn =
const sidebar =
const main =
const navbar =

toggleBtn.addEventListener('click', () => {



});
</script>
{% block extra_js %}{% endblock %}
</body>
</html>

pythondjangowebapplication
Автор

CREATE TABLE TMOL.LOGINHISTORY
(
ID NUMBER,
USERID NUMBER,
IP_ADDRESS VARCHAR2(50 BYTE),
LOGIN_TIME DATE,
ACTION VARCHAR2(10 BYTE)
)
TABLESPACE TMOL_DATA;


CREATE UNIQUE INDEX TMOL.PK_LOGINHIST ON TMOL.LOGINHISTORY
(ID)
TABLESPACE TMOL_IDX;


CREATE OR REPLACE TRIGGER TMOL.loginhist_trig
BEFORE INSERT ON TMOL.LOGINHISTORY
FOR EACH ROW
BEGIN
:new.id := login_seq.NEXTVAL;
END;
/


ALTER TABLE TMOL.LOGINHISTORY ADD (
CONSTRAINT PK_LOGINHIST
PRIMARY KEY
(ID)
USING INDEX
TABLESPACE TMOL_IDX);

ALTER TABLE TMOL.LOGINHISTORY ADD (
CONSTRAINT FK_USER_USERID
FOREIGN KEY (USERID)
REFERENCES TMOL.AUTH_USER (ID));

pythondjangowebapplication
Автор

sequence

CREATE SEQUENCE TMOL.LOGIN_SEQ
START WITH 141
MAXVALUE
MINVALUE 1
NOCYCLE
CACHE 20
NOORDER;

pythondjangowebapplication