Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

DJANGO EDU EMPOWERING WITH

LEARNING MANAGEMENT SYSTEM

A project report submitted to the BHARATHIDASAN


UNIVERSITY, Tiruchirappalli
in partial fulfillment of the requirements for the award of the degree of

MASTER OF COMPUTER APPLICATION

Submitted by

ASKAR MUJIF I

(Register Number – 22MCA07)

Under the Supervision and Guidance of


Dr. K. MUTHURAMALINGAM, Ph.D.,
Assistant Professor
School of Computer Science, Engineering & Applications Bharathidasan
University, Tiruchirappalli – 620 023

SCHOOL OF COMPUTER SCIENCE, ENGINEERING & APPLICATIONS


BHARATHIDASAN UNIVERSITY
TIRUCHIRAPPALLI – 620 023
MAY-2024

1
School of Computer Science, Engineering & Applications
Bharathidasan University
Tiruchirappalli – 620 023

CERTIFICATE

This is to certify that the major project work entitled “DJANGO EDU
EMPOWERING WITH LEARNING MANAGEMENT SYSTEM” is a bonafide
work done by Mr. JEGATHEESAN P, Reg. No: 22MSCDS11 in partial fulfillment
of the requirement for the award of the degree of “MASTER OF COMPUTER
APPLICATION” under the guidance of DR. K.MUTHURAMALIGAM, Ph.D.,
Assistance Professor, School of Computer Science, Engineering & Applications,
Bharathidasan University, Tiruchirappalli–620 023 during the academic year 2023 –
2024.

Signature of the Guide Signature of the HOD

Submitted for the Dept of Computer Science, Bharathidasan University Project


evaluation and viva-voice examination held on at
Bharathidasan University, Tiruchirappalli.

Signature of the Internal Examiner Signature of the External Examiner

2
ACKNOWLEDGEMENT

First and foremost, I would like to thank God Almighty for the abundant shower
of grace blessings on me throughout my entire project.

I wish to express my deep sense of gratitude to Dr. G. Gopinath,


MCA., Ph.D., Professor and Head, School of Computer Science,
Engineering and Applications, Bharathidasan University,
Tiruchirappalli-23 for giving me this opportunity to do this project.

I would like to express my genuine regard and respect to my project


guide DR. K.MUTHURAMALIGAM, Ph.D., Assistance Professor,
School of Computer Science, Engineering & Applications,
Bharathidasan University, Tiruchirappalli-23 for the
encouragement, guidance, inspiration, and constructive suggestions
that help me in carrying out this project successfully.

It is my duty to express my thanks to all Teaching and Non-Teaching Staff


members of Department of Computer Science & Applications, Bharathidasan
University, Tiruchirappalli-23 those who offered me help directly and indirectly by
their suggestions.

Finally, I would like to thank my beloved family members, friends those who
extended support towards the successful completion of my project.

(ASKAR MUJIF I)
22MCA07

3
S.NO TABLE OF CONTENTS PAGE.NO

i) Introduction

ii) Scope

1 Abstract

2 System OverView

3 Setting Up The Development Environment

4 User Authentication And Authorization

5 Course Management

6 Attendendance And Leave Management

7 System Administration

8 Conclusion

9 Appendix

i) Source Code

ii) O/P Screenshots

4
i) INTRODUCTION

This Learning Management System (LMS) is built using Django, a high-level


Python web framework known for its speed, security, and scalability. This LMS
empowers learners and instructors to achieve their educational goals through a
user-friendly and feature-rich platform.

Engaging Learning Environment: Our LMS fosters a stimulating learning


environment with interactive courses, multimedia content, and collaborative
tools.
Personalized Learning Paths: The system caters to individual needs by
recommending courses tailored to specific interests and learning objectives.
Streamlined Course Management: Instructors can easily create, deliver, and
manage courses, leveraging efficient content organization and assessment tools.
Performance Tracking and Reporting: The LMS provides valuable insights
into learner progress and course effectiveness through comprehensive reports
and analytics.

ii) SCOPE

User Management: A robust system for user registration, authentication, and


authorization for learners, instructors, and administrators.
Course Creation and Management: Tools for instructors to develop and
manage courses, including content upload, organization, and structuring.
Communication and Collaboration: Tools for fostering communication and
collaboration among learners and instructors, including discussion forums,
messaging functionalities, and real-time collaboration features.
Administration Panel: A comprehensive dashboard for administrators to
manage user accounts, courses, settings, and access reports.

5
1) ABSTRACT

“The rapid advancement of digital technologies has transformed the landscape


of education, necessitating the development of robust learning management
systems (LMS) to facilitate online teaching and learning. This project aims to
design and implement a comprehensive LMS using the Django web framework,
tailored to the needs of educational institutions and learners alike”.

The primary objectives of the project are to create a user-friendly platform for
course management, content delivery, assessment, and collaboration.
Leveraging Django's powerful features, the system provides secure user
authentication and role-based access control to ensure privacy and data integrity.
Course instructors can easily create and manage courses, upload diverse content
types, such as documents and videos, and engage students through interactive
assessments and communication tools.

The project adopts an iterative development approach, employing best practices


in software engineering, including test-driven development and continuous
integration, to ensure code quality and reliability. Additionally, user feedback
and usability testing are integrated into the development process to enhance the
user experience and address evolving needs.

The expected outcomes of the project include a fully functional LMS prototype
with essential features implemented, along with documentation detailing system
architecture, installation instructions, and user guides. The system's scalability,
extensibility, and performance are evaluated to support future enhancements and
deployment in educational settings.

IIn conclusion, the proposed “learning management system” serves as a


valuable tool for educators and learners, empowering them to engage in
dynamic and personalized online learning experiences. Through the fusion of
Django's versatility and educational expertise, the project contributes to the
advancement of digital education and lifelong learning

2) SYSTEM OVERVIEW
6
Course Creation and Management :
Creating a New Course:
Provide a simple form or interface for instructors to create new courses.
Include fields for course title, description, objectives, prerequisites, and
duration.
Allow instructors to upload a course image or banner for visual identification.

Adding Course Details:


Once a course is created, allow instructors to add or edit details.
Include options for instructors to specify the course schedule, including start
and end dates, class times, and recurring events if applicable.
Provide a text editor for instructors to enter a detailed course description that
outlines the course content, learning outcomes, and any additional information
students should know.
Setting Up Course Schedule and Deadlines:
Include a calendar or scheduling tool for instructors to set up course events,
deadlines for assignments and quizzes, and other important dates.
Allow instructors to send notifications to students about upcoming events and
deadlines.
Enabling Course Enrollment:
Provide a way for students to enroll in courses, either through self-enrollment or
by invitation from the instructor or administrator.
Include options for instructors to set enrollment limits and manage waitlists if
necessary.
Allow instructors to monitor enrollment status and manage student access to
course materials.
Monitoring Student Progress:
Include dashboards or reports for instructors to track student progress, including
participation, completion of assignments and quizzes, and grades.

User Management :
User Registration:
7
Provide a registration form for new users to create an account.
Include fields for basic information such as name, email address, and password.
Implement email verification to validate user accounts.
User Authentication:
Implement authentication mechanisms to verify the identity of users.
Provide options for users to reset their passwords if forgotten.
User Roles and Permissions:
Define different user roles such as student, instructor, administrator, and guest.
Assign appropriate permissions to each role, such as access to course materials,
grading, and administrative functions.
User Profiles:
Allow users to create and manage their profiles, including updating personal
information and uploading a profile picture.
Display user profiles publicly (optional) to encourage interaction and
networking among users.
User Enrollment:
Enable users to enroll in courses either by self-enrollment or by invitation from
instructors or administrators.
Provide options for users to view their enrolled courses and access course
materials.
Managing User Accounts:
Provide administrators with tools to manage user accounts, including creating,
editing, and deleting accounts.
Allow administrators to suspend or deactivate accounts if necessary.

8
Setting Up Course Schedule and Deadlines :
Include a calendar or scheduling tool for instructors to set up course events,
deadlines for assignments and quizzes, and other important dates.
Allow instructors to send notifications to students about upcoming events and
deadlines.

Setting Deadlines:
Enable instructors to set deadlines for assignments, quizzes, and other activities.
Provide options for instructors to specify late submission policies (e.g.,
penalties for late submissions).
Event Reminders:
Implement reminders for upcoming events and deadlines.
Allow users to set their preferred notification settings (e.g., email, in-app
notifications).
Integration with Course Materials:
Link course events to corresponding course materials (e.g., lecture slides,
reading materials) for easy access.
Provide options for instructors to attach additional resources or instructions to
events.
Student View:
Display the course calendar to students so they can see upcoming events and
deadlines.
Provide students with the ability to add events to their personal calendars.
Course Progress Tracking:
Use the course calendar to track student progress and attendance.
Generate reports on student participation and completion of course activities.

9
Course Material Organization :
Organize course materials into logical units or modules based on topics or
lessons.
Provide a hierarchical structure to navigate through different sections of the
course.
Content Types and Formats:
Support various content types such as text, images, videos, presentations, and
documents.
Ensure compatibility with popular formats and players for seamless playback
and viewing.
Content Creation and Editing:
Provide tools for instructors to create and edit course materials directly within
the LMS.
Support collaborative content creation by allowing multiple instructors or
authors to contribute.
Content Versioning and History:
Implement version control to track changes made to course materials over time.
Allow users to view and restore previous versions of course materials if needed.
Content Permissions and Access Control:
Set permissions for who can access and edit course materials based on roles
(e.g., instructor, student, administrator).
Ensure that sensitive or copyrighted materials are protected and accessible only
to authorized users.
Content Archiving and Deletion:
Provide options for archiving or deleting course materials once they are no
longer needed.
Include safeguards to prevent accidental deletion of important course materials.

1
0
3) SETTING UP THE DEVELOPMENT
ENVIRONMENT CONTENT:
Choose a Development Platform:
Select a platform for development, such as Windows, macOS, or Linux, based
on your team's preferences and requirements.
install Python:
Download and install the latest version of Python from the official website
(https://www.python.org/).
Add Python to your system's PATH to make it accessible from the command
line.
Install Django
Use pip, the Python package installer, to install Django by running the following
command:
PIP INSTALL DJANGO

Install Django :
Use pip, the Python package installer, to install Django by running the following
command:
python -m venv env

Activate the virtual environment:


On Windows: env\Scripts\activate
On macOS/Linux: source env/bin/activate

Create a Django Project:


Use the django-admin command to create a new Django project:
django-admin startproject mylms

1
1
Navigate into the project directory :
Cd lms
Install Additional Dependencies:
Depending on your project requirements, you may need to install additional
Python packages. Use pip to install them.
pip install <package-name>

Set Up Database:
Configure your database settings in the settings.py file. Django supports various
databases, including SQLite, PostgreSQL, MySQL, and Oracle.
Create the database and apply migrations :
python manage.py migrate
Create a Django App:
python manage.py startapp courses

Run the Development Server :


Start the Django development server to test your application:
python manage.py runserver
Access your LMS application in a web browser at
http://localhost:8000/.
Development Tools:
Use an Integrated Development Environment (IDE) such as PyCharm,
Visual Studio Code, or Atom for coding and debugging.
Use version control systems like Git to manage your project's source
code and collaborate with team members.

1
2
4) User Authentication And Authorization :
User Authentication:
Explain the process by which users are verified and authenticated when
accessing the LMS.
Describe the authentication methods used, such as username/password, email
verification, or third-party authentication (e.g., OAuth).
Provide instructions for users on how to register and authenticate their accounts.

User Authorization:
Define user roles and permissions within the LMS, such as student, instructor,
administrator, and guest.
Explain the access rights and permissions associated with each role, including
what actions users can perform (e.g., view courses, create assignments, manage
users).
Describe how users are assigned roles and permissions, either manually by
administrators or automatically based on predefined rules.

Authentication Mechanisms:
Describe the security mechanisms used to protect user authentication, such as
encryption (e.g., SSL/TLS), password hashing, and secure token exchange.
Explain how the LMS handles user sessions and cookies to maintain
authentication state.

Password Management:
Provide guidelines for users on creating strong passwords and keeping
them secure.
Explain the password reset process and any security measures in place
to prevent unauthorized password changes.

1
3
Account Lockout and Recovery:
Describe the account lockout policy, including the number of failed
login attempts allowed before an account is locked.
Explain the account recovery process for users who have forgotten
their passwords or are locked out of their accounts.

Security Best Practices:


Provide best practices for users to enhance the security of their
accounts, such as enabling two-factor authentication (2FA) and
keeping their contact information up to date.
Explain the importance of logging out of the LMS when not in use
and avoiding accessing the system from public or shared devices.

Compliance and Regulations :


Ensure that the authentication and authorization mechanisms comply
with relevant regulations and standards, such as GDPR, CCPA, and
FERPA, regarding user data protection and privacy.
Describe how user data is handled and stored securely in accordance
with these regulations.

Troubleshooting and Support :


Provide troubleshooting steps for common authentication and
authorization issues, such as login failures or account lockouts.
Explain how users can contact support for assistance with
authentication and authorization problems.

1
4
5) COURSE MANAGEMENT:
Course Creation:
Provide instructors with tools to create new courses within the LMS.
Include fields for course title, description, objectives, prerequisites,
and duration.

Course Settings:
Allow instructors to configure course settings, such as enrollment
options, visibility, and access permissions.
Provide options for instructors to set up grading scales, attendance
policies, and other course-specific settings.

Course Organization:
Organize course materials into modules or units based on topics or
lessons.
Provide a hierarchical structure to navigate through different sections
of the course.

Course Materials:
Allow instructors to upload and manage course materials such as
lectures, readings, videos, and quizzes.
Provide options for instructors to set access permissions for each
material (e.g., available to all students, enrolled students only).

1
5
Enrollment Management:
Allow instructors to manage course enrollment, including approving
or rejecting enrollment requests.
Provide options for instructors to set enrollment limits and manage
waitlists if necessary.

Communication Tools:
Include communication tools such as discussion forums,
announcements, and messaging for instructors to interact with
students.
Enable instructors to send notifications to students about course
updates, deadlines, and announcements.

Assessment and Grading:


Provide tools for instructors to create quizzes, assignments, and
exams.
Allow instructors to grade student submissions and provide feedback.

Progress Tracking :
Track student progress and participation in courses.
Generate reports on student grades, completion rates, and
participation.

1
6
Course Collaboration:
Enable collaboration among students through group projects,
discussions, and peer reviews.
Provide tools for instructors to monitor and participate in course
collaborations.

Course Evaluation:
Collect feedback from students about the course content, structure,
and instructor performance.
Use feedback to improve the course and enhance the learning
experience.
Course Archiving and Deletion:
Provide options for archiving or deleting courses once they are
completed or no longer active.
Include safeguards to prevent accidental deletion of courses or course
materials.

Course Catalog:
Provide a course catalog where users can browse and search for
available courses.
Include course descriptions, objectives, and prerequisites to help users
make informed decisions.

1
7
6) ATTENDANCE AND LEAVE MANAGEMENT:

Attendance Tracking :
Provide instructors with tools to track student attendance for lectures,
classes, or virtual sessions.
Include options for manual entry or automated tracking using check-
ins or QR codes.
Allow instructors to view attendance records and generate reports.

Leave Request Management :


Allow students or employees to submit leave requests through the
LMS.
Include fields for leave type (e.g., sick leave, vacation), start and end
dates, and reason for leave.
Provide options for approving or rejecting leave requests by
instructors or managers.

Leave Balances:
Display leave balances for students or employees, showing the
remaining days or hours of each leave type.
Update leave balances automatically based on approved leave
requests.

Leave Calendar:
Provide a calendar view for students or employees to view upcoming
leave requests and their own leave schedule.
Include options to filter and search for leave requests by date, leave
type, or status.
1
8
Leave Policies:
Define and communicate leave policies within the LMS, including
rules for applying for leave, approval process, and consequences for
unauthorized leave.
Ensure that leave policies comply with legal requirements and
organizational policies.

Notifications:
Send notifications to students or employees about upcoming leave
requests, approval status, and changes to leave balances.
Allow users to customize notification preferences for leave-related
events.

Integration with HR Systems:


Integrate leave management with existing HR systems to ensure
consistency and accuracy of leave data.
Sync leave balances and approved leave requests with payroll systems
for processing.

Reporting and Analytics:


Generate reports on attendance patterns, leave utilization, and trends
over time.
Use analytics to identify patterns of absenteeism or leave abuse and
take corrective actions.

1
9
Compliance and Legal Requirements:
Ensure that leave management practices comply with legal
requirements and regulations, such as labor laws and company
policies.
Provide options for users to report violations of leave policies or seek
assistance in case of disputes.

Accessibility and Usability:


Ensure that the leave management features are accessible to all users,
including those with disabilities.
Design a user-friendly interface with intuitive navigation and controls.

Mobile Accessibility:
Ensure that attendance and leave management features are accessible
via mobile devices, allowing users to manage their attendance and
leave requests on the go.
Provide a mobile app or responsive web design for easy access from
smartphones and tablets.

Integration with Payroll:


Integrate attendance and leave management with payroll systems to
calculate employee salaries based on attendance and leave data.
Ensure that leave balances and attendance records are accurately
reflected in payroll calculations.

2
0
7)SYSTEM ADMINISTRATION:

Server Setup and Configuration:


Select a reliable hosting provider or set up your own server
infrastructure.
Install and configure the necessary software components, such as web
servers (e.g., Apache, Nginx), database servers (e.g., MySQL,
PostgreSQL), and application servers (e.g., Django, Node.js).

System Monitoring and Maintenance:


Implement monitoring tools to track system performance, uptime, and
resource usage.
Schedule regular maintenance tasks, such as software updates,
security patches, and database backups.

Security Management :
Implement security measures to protect the LMS from unauthorized
access, data breaches, and other security threats.
Use firewalls, intrusion detection systems, and encryption to secure
data in transit and at rest.

User and Access Management:


Manage user accounts, roles, and permissions within the LMS.
Ensure that user authentication and authorization mechanisms are
secure and compliant with regulations.

2
1
Data Management:
Implement data backup and recovery procedures to protect against
data loss.
Monitor database performance and optimize queries to improve
system responsiveness.

System Integration:
Integrate the LMS with other systems and tools, such as student
information systems (SIS), HR systems, and content repositories.
Ensure that data is exchanged securely and accurately between
systems.

Scalability and Performance:


Design the system to be scalable to accommodate growth in users and
content.
Monitor system performance and optimize resource allocation to
ensure optimal performance.

Disaster Recovery:
Develop and maintain a disaster recovery plan to quickly restore the
LMS in the event of a system failure or disaster.
Test the disaster recovery plan regularly to ensure its effectiveness.

2
2
8)CONCLUSION:

In conclusion, effective system administration is essential for the


successful operation of a Learning Management System (LMS). A
well-managed LMS ensures smooth performance, data security, and
user satisfaction. Key aspects of system administration include server
setup and configuration, system monitoring and maintenance, security
management, user and access management, data management, system
integration, scalability and performance, disaster recovery,
compliance and regulations, documentation, and training. By focusing
on these areas, you can ensure that your LMS operates efficiently,
meets regulatory requirements, and provides a positive learning
experience for users.

2
3
SOURCE CODE:

import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'college_management_system.settings')
application = get_asgi_application()

SETTINGS.PY

# import dj_database_url
import os
from pathlib import Path

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


BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'f2zx8*lb*em*-
*b+!&1lpp&$_9q9kmkar+l3x90do@s(+sr&x7' # Consider using your secret
key

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


DEBUG = True

# ALLOWED_HOSTS = ['smswithdjango.herokuapp.com']
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
2
4
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',

# Third Part Middleware


'whitenoise.middleware.WhiteNoiseMiddleware',

# My Middleware
'main_app.middleware.LoginCheckMiddleWare',
]

ROOT_URLCONF = 'college_management_system.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['main_app/templates'], #My App Templates
'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',
],
},
},

2
5
]

WSGI_APPLICATION = 'college_management_system.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'django',
# 'USER': os.environ.get('DB_USER'),
# 'PASSWORD': os.environ.get('DB_PASS'),
# 'HOST': '127.0.0.1',
# 'PORT': '3307'
#}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-
validators
if not DEBUG:
AUTH_PASSWORD_VALIDATORS = []
else:
2
6
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
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

2
7
USE_TZ = True

# Static files (CSS, JavaScript, Images)


# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static')


MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
AUTH_USER_MODEL = 'main_app.CustomUser'
AUTHENTICATION_BACKENDS =
['main_app.EmailBackend.EmailBackend']
TIME_ZONE = 'Africa/Lagos'

# EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
# EMAIL_FILE_PATH = os.path.join(BASE_DIR, "sent_mails")

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587

EMAIL_HOST_USER = os.environ.get('EMAIL_ADDRESS')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_USE_TLS = True

2
8
# DEFAULT_FROM_EMAIL = "School Management System
<admin@admin.com>"

# STATICFILES_STORAGE =
'whitenoise.storage.CompressedManifestStaticFilesStorage'

# prod_db = dj_database_url.config(conn_max_age=500)
# DATABASES['defa
ult'].update(prod_db)

URLS.PY

from django.contrib import admin


from django.urls import path, include
from django.conf.urls.static import static
from . import settings

urlpatterns = [
path("", include('main_app.urls')),
path("accounts/", include("django.contrib.auth.urls")),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) +
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

2
9
WSGI.PY
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'college_management_system.settings')
application = get_wsgi_application()

APP.VIEWS:
import json
import requests
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render, reverse
from django.views.decorators.csrf import csrf_exempt

from .EmailBackend import EmailBackend


from .models import Attendance, Session, Subject

# Create your views here.

def login_page(request):
if request.user.is_authenticated:
if request.user.user_type == '1':

3
0
return redirect(reverse("admin_home"))
elif request.user.user_type == '2':
return redirect(reverse("staff_home"))
else:
return redirect(reverse("student_home"))
return render(request, 'main_app/login.html')

def doLogin(request, **kwargs):


if request.method != 'POST':
return HttpResponse("<h4>Denied</h4>")
else:
#Google recaptcha
captcha_token = request.POST.get('g-recaptcha-response')
captcha_url = "https://www.google.com/recaptcha/api/siteverify"
captcha_key = "6LfswtgZAAAAABX9gbLqe-d97qE2g1JP8oUYritJ"
data = {
'secret': captcha_key,
'response': captcha_token
}
# Make request
try:
captcha_server = requests.post(url=captcha_url, data=data)
response = json.loads(captcha_server.text)
if response['success'] == False:
messages.error(request, 'Invalid Captcha. Try Again')
return redirect('/')

3
1
except:
messages.error(request, 'Captcha could not be verified. Try Again')
return redirect('/')

#Authenticate
user = EmailBackend.authenticate(request,
username=request.POST.get('email'),
password=request.POST.get('password'))
if user != None:
login(request, user)
if user.user_type == '1':
return redirect(reverse("admin_home"))
elif user.user_type == '2':
return redirect(reverse("staff_home"))
else:
return redirect(reverse("student_home"))
else:
messages.error(request, "Invalid details")
return redirect("/")

def logout_user(request):
if request.user != None:
logout(request)
return redirect("/")

3
2
@csrf_exempt
def get_attendance(request):
subject_id = request.POST.get('subject')
session_id = request.POST.get('session')
try:
subject = get_object_or_404(Subject, id=subject_id)
session = get_object_or_404(Session, id=session_id)
attendance = Attendance.objects.filter(subject=subject,
session=session)
attendance_list = []
for attd in attendance:
data = {
"id": attd.id,
"attendance_date": str(attd.date),
"session": attd.session.id
}
attendance_list.append(data)
return JsonResponse(json.dumps(attendance_list), safe=False)
except Exception as e:
return None

def showFirebaseJS(request):
data = """
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase
libraries
// are not available in the service worker.
3
3
importScripts('https://www.gstatic.com/firebasejs/7.22.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.22.1/firebase-
messaging.js');

// Initialize the Firebase app in the service worker by passing in


// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: "AIzaSyBarDWWHTfTMSrtc5Lj3Cdw5dEvjAkFwtM",
authDomain: "sms-with-django.firebaseapp.com",
databaseURL: "https://sms-with-django.firebaseio.com",
projectId: "sms-with-django",
storageBucket: "sms-with-django.appspot.com",
messagingSenderId: "945324593139",
appId: "1:945324593139:web:03fa99a8854bbd38420c86",
measurementId: "G-2F2RXTL9GT"
});

// Retrieve an instance of Firebase Messaging so that it can handle


background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const notification = JSON.parse(payload);
const notificationOption = {
body: notification.body,
icon: notification.icon
}
3
4
return self.registration.showNotification(payload.notification.title,
notificationOption);
});
"""
return HttpResponse(data, content_type='application/javascript')

APP.VIEWS:

from django.urls import path

from main_app.EditResultView import EditResultView

from . import hod_views, staff_views, student_views, views

urlpatterns = [
path("", views.login_page, name='login_page'),
path("get_attendance", views.get_attendance,
name='get_attendance'),
path("firebase-messaging-sw.js", views.showFirebaseJS,
name='showFirebaseJS'),
path("doLogin/", views.doLogin, name='user_login'),
path("logout_user/", views.logout_user, name='user_logout'),
path("admin/home/", hod_views.admin_home,
name='admin_home'),
path("staff/add", hod_views.add_staff, name='add_staff'),

3
5
path("course/add", hod_views.add_course,
name='add_course'),
path("send_student_notification/",
hod_views.send_student_notification,
name='send_student_notification'),
path("send_staff_notification/",
hod_views.send_staff_notification,
name='send_staff_notification'),
path("add_session/", hod_views.add_session,
name='add_session'),
path("admin_notify_student",
hod_views.admin_notify_student,
name='admin_notify_student'),
path("admin_notify_staff", hod_views.admin_notify_staff,
name='admin_notify_staff'),
path("admin_view_profile", hod_views.admin_view_profile,
name='admin_view_profile'),
path("check_email_availability",
hod_views.check_email_availability,
name="check_email_availability"),
path("session/manage/", hod_views.manage_session,
name='manage_session'),
path("session/edit/<int:session_id>",
hod_views.edit_session, name='edit_session'),
path("student/view/feedback/",
hod_views.student_feedback_message,
name="student_feedback_message",),

3
6
path("staff/view/feedback/",
hod_views.staff_feedback_message,
name="staff_feedback_message",),
path("student/view/leave/", hod_views.view_student_leave,
name="view_student_leave",),
path("staff/view/leave/", hod_views.view_staff_leave,
name="view_staff_leave",),
path("attendance/view/", hod_views.admin_view_attendance,
name="admin_view_attendance",),
path("attendance/fetch/", hod_views.get_admin_attendance,
name='get_admin_attendance'),
path("student/add/", hod_views.add_student,
name='add_student'),
path("subject/add/", hod_views.add_subject,
name='add_subject'),
path("staff/manage/", hod_views.manage_staff,
name='manage_staff'),
path("student/manage/", hod_views.manage_student,
name='manage_student'),
path("course/manage/", hod_views.manage_course,
name='manage_course'),
path("subject/manage/", hod_views.manage_subject,
name='manage_subject'),
path("staff/edit/<int:staff_id>", hod_views.edit_staff,
name='edit_staff'),
path("staff/delete/<int:staff_id>",
hod_views.delete_staff, name='delete_staff'),

3
7
path("course/delete/<int:course_id>",
hod_views.delete_course, name='delete_course'),

path("subject/delete/<int:subject_id>",
hod_views.delete_subject, name='delete_subject'),

path("session/delete/<int:session_id>",
hod_views.delete_session, name='delete_session'),

path("student/delete/<int:student_id>",
hod_views.delete_student, name='delete_student'),
path("student/edit/<int:student_id>",
hod_views.edit_student, name='edit_student'),
path("course/edit/<int:course_id>",
hod_views.edit_course, name='edit_course'),
path("subject/edit/<int:subject_id>",
hod_views.edit_subject, name='edit_subject'),
# Staff
path("staff/home/", staff_views.staff_home,
name='staff_home'),
path("staff/apply/leave/", staff_views.staff_apply_leave,
name='staff_apply_leave'),
path("staff/feedback/", staff_views.staff_feedback,
name='staff_feedback'),

3
8
path("staff/view/profile/", staff_views.staff_view_profile,
name='staff_view_profile'),
path("staff/attendance/take/",
staff_views.staff_take_attendance,
name='staff_take_attendance'),
path("staff/attendance/update/",
staff_views.staff_update_attendance,
name='staff_update_attendance'),
path("staff/get_students/", staff_views.get_students,
name='get_students'),
path("staff/attendance/fetch/",
staff_views.get_student_attendance,
name='get_student_attendance'),
path("staff/attendance/save/",
staff_views.save_attendance, name='save_attendance'),
path("staff/attendance/update/",
staff_views.update_attendance, name='update_attendance'),
path("staff/fcmtoken/", staff_views.staff_fcmtoken,
name='staff_fcmtoken'),
path("staff/view/notification/",
staff_views.staff_view_notification,
name="staff_view_notification"),
path("staff/result/add/", staff_views.staff_add_result,
name='staff_add_result'),
path("staff/result/edit/", EditResultView.as_view(),
name='edit_student_result'),
path('staff/result/fetch/', staff_views.fetch_student_result,
3
9
name='fetch_student_result'),

# Student
path("student/home/", student_views.student_home,
name='student_home'),
path("student/view/attendance/",
student_views.student_view_attendance,
name='student_view_attendance'),
path("student/apply/leave/",
student_views.student_apply_leave,
name='student_apply_leave'),
path("student/feedback/", student_views.student_feedback,
name='student_feedback'),
path("student/view/profile/",
student_views.student_view_profile,
name='student_view_profile'),
path("student/fcmtoken/", student_views.student_fcmtoken,
name='student_fcmtoken'),
path("student/view/notification/",
student_views.student_view_notification,
name="student_view_notification"),
path('student/view/result/', student_views.student_view_result,
name='student_view_result'),
]

4
0
FORMS.PY

from django import forms


from django.forms.widgets import DateInput, TextInput

from .models import *

class FormSettings(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(FormSettings, self).__init__(*args, **kwargs)
# Here make some changes such as:
for field in self.visible_fields():
field.field.widget.attrs['class'] = 'form-control'

class CustomUserForm(FormSettings):
email = forms.EmailField(required=True)
gender = forms.ChoiceField(choices=[('M', 'Male'), ('F',
'Female')])
first_name = forms.CharField(required=True)
last_name = forms.CharField(required=True)
address = forms.CharField(widget=forms.Textarea)
4
1
password =
forms.CharField(widget=forms.PasswordInput)
widget = {
'password': forms.PasswordInput(),
}
profile_pic = forms.ImageField()

def __init__(self, *args, **kwargs):


super(CustomUserForm, self).__init__(*args,
**kwargs)

if kwargs.get('instance'):
instance = kwargs.get('instance').admin.__dict__
self.fields['password'].required = False
for field in CustomUserForm.Meta.fields:
self.fields[field].initial = instance.get(field)
if self.instance.pk is not None:
self.fields['password'].widget.attrs['placeholder']
= "Fill this only if you wish to update password"

def clean_email(self, *args, **kwargs):


formEmail = self.cleaned_data['email'].lower()
if self.instance.pk is None: # Insert

4
2
if
CustomUser.objects.filter(email=formEmail).exists():
raise forms.ValidationError(
"The given email is already registered")
else: # Update
dbEmail = self.Meta.model.objects.get(
id=self.instance.pk).admin.email.lower()
if dbEmail != formEmail: # There has been
changes
if
CustomUser.objects.filter(email=formEmail).exists():
raise forms.ValidationError("The given email
is already registered")

return formEmail

class Meta:
model = CustomUser
fields = ['first_name', 'last_name', 'email', 'gender',
'password','profile_pic', 'address' ]

class StudentForm(CustomUserForm):
def __init__(self, *args, **kwargs):
4
3
super(StudentForm, self).__init__(*args, **kwargs)

class Meta(CustomUserForm.Meta):
model = Student
fields = CustomUserForm.Meta.fields + \
['course', 'session']

class AdminForm(CustomUserForm):
def __init__(self, *args, **kwargs):
super(AdminForm, self).__init__(*args, **kwargs)

class Meta(CustomUserForm.Meta):
model = Admin
fields = CustomUserForm.Meta.fields

class StaffForm(CustomUserForm):
def __init__(self, *args, **kwargs):
super(StaffForm, self).__init__(*args, **kwargs)

class Meta(CustomUserForm.Meta):
model = Staff
4
4
fields = CustomUserForm.Meta.fields + \
['course' ]

class CourseForm(FormSettings):
def __init__(self, *args, **kwargs):
super(CourseForm, self).__init__(*args, **kwargs)

class Meta:
fields = ['name']
model = Course

class SubjectForm(FormSettings):

def __init__(self, *args, **kwargs):


super(SubjectForm, self).__init__(*args, **kwargs)

class Meta:
model = Subject
fields = ['name', 'staff', 'course']

4
5
class SessionForm(FormSettings):
def __init__(self, *args, **kwargs):
super(SessionForm, self).__init__(*args, **kwargs)

class Meta:
model = Session
fields = '__all__'
widgets = {
'start_year': DateInput(attrs={'type': 'date'}),
'end_year': DateInput(attrs={'type': 'date'}),
}

class LeaveReportStaffForm(FormSettings):
def __init__(self, *args, **kwargs):
super(LeaveReportStaffForm, self).__init__(*args,
**kwargs)

class Meta:
model = LeaveReportStaff
fields = ['date', 'message']
widgets = {
'date': DateInput(attrs={'type': 'date'}),
4
6
}

class FeedbackStaffForm(FormSettings):

def __init__(self, *args, **kwargs):


super(FeedbackStaffForm, self).__init__(*args,
**kwargs)

class Meta:
model = FeedbackStaff
fields = ['feedback']

class LeaveReportStudentForm(FormSettings):
def __init__(self, *args, **kwargs):
super(LeaveReportStudentForm, self).__init__(*args,
**kwargs)

class Meta:
model = LeaveReportStudent
fields = ['date', 'message']
widgets = {

4
7
'date': DateInput(attrs={'type': 'date'}),
}

class FeedbackStudentForm(FormSettings):

def __init__(self, *args, **kwargs):


super(FeedbackStudentForm, self).__init__(*args,
**kwargs)

class Meta:
model = FeedbackStudent
fields = ['feedback']

class StudentEditForm(CustomUserForm):
def __init__(self, *args, **kwargs):
super(StudentEditForm, self).__init__(*args,
**kwargs)

class Meta(CustomUserForm.Meta):
model = Student
fields = CustomUserForm.Meta.fields

4
8
class StaffEditForm(CustomUserForm):
def __init__(self, *args, **kwargs):
super(StaffEditForm, self).__init__(*args, **kwargs)

class Meta(CustomUserForm.Meta):
model = Staff
fields = CustomUserForm.Meta.fields

class EditResultForm(FormSettings):
session_list = Session.objects.all()
session_year = forms.ModelChoiceField(
label="Session Year", queryset=session_list,
required=True)

def __init__(self, *args, **kwargs):


super(EditResultForm, self).__init__(*args,
**kwargs)

class Meta:
model = StudentResult

4
9
fields = ['session_year', 'subject', 'student', 'test',
'exam']

-------------------- *********************-----------------------

5
0
OUTPUT:

STUDENT DASHBOARD:

LOGIN PAGE:

5
1
ADMIN DASHBOARD:

STAFF DASHBOARD:

5
2

You might also like