Python Django Project – Online Voting System

Python course with 57 real-time projects - Learn Python

FREE Online Courses: Click, Learn, Succeed, Start Now!

An online voting system, also known as e-voting, is a digital platform that allows eligible voters to cast their votes remotely using the internet. It is a modern alternative to traditional paper-based voting methods. With an online voting system, voters can access the voting process through a secure website or a dedicated voting application.

About Python Django Online Voting System

The objective of a Python Django online voting system is to provide a convenient and efficient method for eligible voters to cast their votes remotely using the internet.

Prerequisite For Online Voting System Using Python Django

  • A solid understanding of the Python programming language and the Django web framework is necessary.
  • A strong understanding of HTML, CSS, and JavaScript is required to develop the project’s user interface.
  • Relational Database: You will need to have a good understanding of relational databases, such as SQLite, MySQL, or PostgreSQL, to create and manage the database for the Online voting system project.

Download Python Django Online Voting System Project

Please download the source code of the Python Django Online Voting System: Python Django Online Voting System Project Code.

Project Setup

Minimum system configuration:

  • The operating system requirements include Windows 7 or later, macOS 10.11 or later, or a modern operating system.
  • Linux distribution.
  • Processor: Intel Core i3 or equivalent.
  • RAM: 4 GB or more
  • Disk Space: 5 GB or more.
  • Browsers such as Google Chrome, Mozilla Firefox, or Microsoft Edge can be used.

Visual Studio Code can be downloaded from the official website.

On the download page, you can select the suitable installer for your operating system (Windows, macOS, or Linux). After downloading the installer, run it and proceed with the installation instructions to install VS Code on your computer.

Here’s a brief explanation of each step, along with the commands to execute:

1. Python should be installed: Download and install the latest version of Python from the official website, following the installation instructions for your operating system.
2. Install pip: Download the get-pip.py script and run python get-pip.py to install pip.
3. Create a virtual environment: Run python -m venv myenv to create a new virtual environment named ‘myenv’.
4. Activate the virtual environment: Run source myenv/bin/activate on Linux/Mac or myenv\Scripts\activate on Windows to activate the virtual environment.
5. Install Django: Run pip install django to install the latest stable version of Django.
6. Verify installation: Run python -m django –version to verify that Django is installed correctly.
7. Create a new Django project: Run django-admin startproject project to create a new Django project named ‘project’.
8. Start the development server: Run python manage.py runserver to start the development server.
That’s it! A working installation of Django should now be in place, and you should be ready to start building your web application.

Steps to Create a “ Python Django Voting System” Project – Let’s Move ahead with this amazing project.

1. Open the terminal fromfolder where we want to create the project. Right click on mouse -> open in terminal -> write “code .” (space is mandatory between code and “.”)

2. Then go to the project folder -> urls.py and inside urls.py of project, do this -> add “include” in import as shown in the code below and add “path(“”, include(“app.urls”))”

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

3. Create urls.py in the app of Pin your Notes project(urls.py is mandatory in both the project and app).

4. In setting.py, add the ‘app name”.

5. Now runserver to check if everything is working or not. If you see the below image, then we are done with the installation part. To runserver, run command in terminal as follows “py manage.py runserver”.

6. Now, create the models.py using the ORM technique as follows.

To create the above field in a database, run the following commands as follows:
● Py manage.py makemigrations
● Py manage.py migrate

The file structure will look like this for our project:
App(main) -> Templates -> app(folder inside app) -> registration.html, login.html, votingpage.html.

Now, execute the project step by step with code as follows:

Steps to Create Django Online Voting System Project – Let’s Move ahead with an amazing project.

1. Open the terminal from the folder where we want to create the project.
Right click on mouse -> open in terminal -> write “code .” (space is mandatory between code and “.”)

2. Then go to the project folder -> urls.py and inside urls.py of project, do this -> add “include” in import as shown in the code below and add “path(“”, include(“app.urls”))”

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("app.urls"))
]

3. Create urls.py in an app of wishlistproject(urls.py is mandatory in both the project and app).

4. In setting.py, add the ‘app name”. In my case, it is the app only as below.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app'
]

5. Now runserver to check, if everything is working or not. If you see below image, then we are done with the installation part. To runserver, run command in terminal as follows “py manage.py runserver”.(if you see the rocket image, then it’s working fine).

6. Now create the models.py using ORM technique as follows.

from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
# Create your models here.
class Questions(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ques = models.CharField(max_length=150)
    option1 = models.CharField(max_length=150)
    option2 = models.CharField(max_length=150)
    option3 = models.CharField(max_length=150)
    option4 = models.CharField(max_length=150)
    vote1 = models.IntegerField(default=0)
    vote2 = models.IntegerField(default=0)
    vote3 = models.IntegerField(default=0)
    vote4 = models.IntegerField(default=0)
    vote = models.IntegerField(default=False, verbose_name="How many object created for this questions?")
    is_closed = models.BooleanField(default=False)

    @property
    def total_votes(self):
        return self.vote1 + self.vote2 + self.vote3 + self.vote4
    
    @property
    def get_winner_option(self):
        options = [self.vote1, self.vote2, self.vote3, self.vote4]
        max_votes = max(options)
        winner_index = options.index(max_votes)
        if options.count(max_votes) > 1:
            return "It's a tie"
        else:
            if winner_index == 0:
                return self.option1
            elif winner_index == 1:
                return self.option2
            elif winner_index == 2:
                return self.option3
            elif winner_index == 3:
                return self.option4
        return

    def __str__(self) -> str:
        return self.ques
    
class Voted(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    voted_question = models.ForeignKey(Questions, on_delete=models.CASCADE)

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.PositiveIntegerField(validators=[MinValueValidator(0)])

To create the above field in a database, run the following commands as follows:

  • Py manage.py makemigrations
  • Py manage.py migrate

7. Create a Registration system
templates/app -> registration.html

<div class="container">
        <h1><u>DataFlair Voting System</u></h1>
        <div class="form-container">
            <h1>Registration</h1>
            <form action="{% url 'registration' %}" method="post">
                {% csrf_token %}
                <input type="text" placeholder="Name" name="uname">
                <input type="email" placeholder="Email" name="email">
                <input type="text" placeholder="Age" name="age">
                <input type="password" placeholder="Password" name="passw">
                <input type="password" placeholder="Confirm Password" name="cpass">
                <button type="submit">Register</button>
            </form>
            <p>Already registered? <a href="{% url 'index' %}">click here</a></p>
        </div>
    </div>

Views.py

def register(request):
    return render(request, "app/registration.html")

def Registration(request):
    if request.method == "POST":
        username = request.POST['uname']
        email = request.POST['email']
        password = request.POST['passw']
        cpassword = request.POST['cpass']
        age = int(request.POST['age'])  # Convert age to an integer

        if password == cpassword:
            new_user = User.objects.create(
            username = username,
            email = email,
            )
            new_user.set_password(password)
            new_user.save()

            return redirect("index")
        return

Urls.py

path("register", views.register, name="register"),
path("registration", views.Registration, name="registration"),

8. Create a login system
Templates.html -> login.html

<div class="container">
        <h1><u>DataFlair Voting System</u></h1>
        <div class="form-container">
            <h1>Login</h1>
            <form action="{% url 'login' %}" method="post">
                {% csrf_token %}
                <input type="text" placeholder="Username" name="uname">
                <input type="password" placeholder="Password" name="password">
                <button type="submit">Login</button>
            </form>
            <p>Not registered? <a href="{% url 'register' %}">click here</a></p>
        </div>
    </div>

Views.py

def Loginview(request):
    if request.method == "POST":
        username = request.POST['uname']
        password = request.POST['password']

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect("show")
        else:
            return HttpResponse("invalid credentials")

Urls.py

path("login", views.Loginview, name="login"),

9. Create a main page where voting can be done(one user can vote one time only).
templates/app -> votingpage.html

<center>
        <h3 style="color: tomato;">
            {% if messages %}
            {% for message in messages %}
            <div>{{ message }}</div>
            {% endfor %}
            {% endif %}
        </h3>
    </center>
    <br><br>
  {% for item in new_ques %}
    <div class="container">
        <form method="post" action="{% url 'votingpage' pk=item.pk %}">
            {% csrf_token %}
            <h2>{{ item.ques }}</h2>
            <label><input type="radio" name="selected_option" value="1">{{ item.option1 }}</label><br>
            <label><input type="radio" name="selected_option" value="2">{{ item.option2 }}</label><br>
            <label><input type="radio" name="selected_option" value="3">{{ item.option3 }}</label><br>
            <label><input type="radio" name="selected_option" value="4">{{ item.option4 }}</label><br>
            <h4>Total Votes: {{item.total_votes}}</h4>
            {% if item.is_closed %}
            <p><strong>Winner: {{ item.get_winner_option }}</strong></p>
            <button class="vote-button" type="button" disabled>
                Voting Closed
            </button>
            {% else %}
            <button class="vote-button" type="submit">
                {% if user_profile.age > 18 %}
                Vote Now
                {% else %}
                Not allowed
                {% endif %}
            </button>
            {% endif %}
        </form>
        <br>
    </div>
    {% endfor %}

Views.py

@login_required(login_url="login")
def Voting(request, pk):
    user = request.user
    ques = get_object_or_404(Questions, pk=pk)
    
    # Check if the user is below 18 years old
    user_profile = UserProfile.objects.get(user=user)
    if user_profile.age < 18:
        messages.warning(request, "Voters below 18 years of age are not allowed to vote.")
        return redirect("votingpage")

    # Check if the user has already voted for this question
    if Voted.objects.filter(user=user, voted_question=ques).exists():
        messages.warning(request, "You have already voted for this question.")
        return redirect("already") 
    else:
        selected_option = request.POST.get('selected_option')
        if selected_option in ['1', '2', '3', '4']:
            setattr(ques, f'vote{selected_option}', getattr(ques, f'vote{selected_option}') + 1)
            ques.save()
            Voted.objects.create(user=user, voted_question=ques)
            messages.success(request, "Your vote has been recorded.")
        else:
            messages.warning(request, "Invalid vote selection.")

        return redirect('show')

@login_required(login_url="login")
def show(request):
    new_ques = Questions.objects.all()
   

    # Check if the user's age is less than 18 and show a warning message
    user_profile = UserProfile.objects.get(user=request.user)
    if user_profile.age < 18:
        messages.warning(request, "Voter below 18 age group is not allowed.")

    return render(request, "app/votingpage.html", {"new_ques": new_ques, "user_profile": user_profile})

Urls.py

path("home", views.home, name="home"),
path("votingpage/<int:pk>", views.Voting, name="votingpage"),
path("showques", views.show, name="show"),

10. For logout process
Views.py

@login_required(login_url="login")
def signout(request):
    logout(request)
    return redirect("index")

Urls.py

path("logout", views.signout, name="logout")

Explanation of the above snippets:

Certainly! Here’s an explanation of each view in the provided code:

1. Index(request):

This view renders the login page (login.html).

2. register(request):

This view renders the registration page (registration.html).

3. Registration(request):

  • This view handles the registration process when the registration form is submitted.
  • It first checks if the passwords provided by the user match.
  • If the passwords match, a new User object is created with the provided username and email.
  • The password is set and encrypted using the set_password method.
  • The new user is saved to the database, and the user is redirected to the login page (index).

4. Loginview(request):

  • This view handles the login process when the login form is submitted.
  • It retrieves the username and password entered by the user.
  • The authenticate function is used to verify the credentials. If the authentication is successful, the user is logged in using the login function, and they are redirected to the “show” page.
  • If the authentication fails, an “invalid credentials” message is displayed.

5. home(request):

  • This view renders the main page (votingpage.html) after the user has successfully logged in.
  • The @login_required decorator ensures that only authenticated users can access this page. If a user is not logged in, they are redirected to the login page.

6. Voting(request, pk):

  • This view handles the process of voting for a specific question.
  • It first retrieves the authenticated user and the question (specified by its primary key pk) using get_object_or_404.
  • It checks if the user has already voted for the question by searching for an existing record in the Voted model.
  • If the user has not voted for the question, the vote count for the question is incremented, and the vote is saved.
  • A new record is created in the Voted model to indicate that the user has voted for that question.
  • The user is then redirected to the “show” page.

7. show(request):

  • This view retrieves all the questions from the Questions model and renders the “votingpage.html” template.
  • The retrieved questions are passed to the template as the context variable new_ques.

8. signout(request):

  • This view handles the logout process.
  • The logout function is called to log out the user.
  • The user is then redirected to the login page (index).

These views, along with the corresponding URL patterns defined in the urlpatterns list, form the routing and logic for the online voting system.

Here is the complete code for Python Django Online Voting System as follows:

templates/app -> registration.html

<!DOCTYPE html>
<html>

<head>
    <title>Registration</title>
    <style>
        body {
            background-color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            background-color: #ffffff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: 300px;
        }

        h1 {
            text-align: center;
        }

        form {
            display: flex;
            flex-direction: column;
        }

        input[type="text"],
        input[type="email"],
        input[type="password"] {
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px;
            background-color: #4caf50;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1><u>DataFlair Voting System</u></h1>
        <div class="form-container">
            <h1>Registration</h1>
            <form action="{% url 'registration' %}" method="post">
                {% csrf_token %}
                <input type="text" placeholder="Name" name="uname">
                <input type="email" placeholder="Email" name="email">
                <input type="text" placeholder="Age" name="age">
                <input type="password" placeholder="Password" name="passw">
                <input type="password" placeholder="Confirm Password" name="cpass">
                <button type="submit">Register</button>
            </form>
            <p>Already registered? <a href="{% url 'index' %}">click here</a></p>
        </div>
    </div>
</body>

</html>

templates/app -> login.html

<!DOCTYPE html>
<html>

<head>
    <title>Login</title>
    <style>
        body {
            background-color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            background-color: #ffffff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: 300px;
        }

        h1 {
            text-align: center;
        }

        form {
            display: flex;
            flex-direction: column;
        }

        input[type="text"],
        input[type="password"] {
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px;
            background-color: #4caf50;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1><u>DataFlair Voting System</u></h1>
        <div class="form-container">
            <h1>Login</h1>
            <form action="{% url 'login' %}" method="post">
                {% csrf_token %}
                <input type="text" placeholder="Username" name="uname">
                <input type="password" placeholder="Password" name="password">
                <button type="submit">Login</button>
            </form>
            <p>Not registered? <a href="{% url 'register' %}">click here</a></p>
        </div>
    </div>
</body>

</html>

templates/ app -> votingpage.html

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <style>
        nav {
            background-color: #f2f2f2;
            height: 60px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
        }

        .logo img {
            height: 40px;
        }

        .username {
            font-size: 18px;
        }

        .container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f2f2f2;
            border-radius: 5px;
        }

        h2 {
            text-align: center;
            margin-bottom: 20px;
        }

        .option {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        input[type="radio"] {
            margin-right: 10px;
        }

        label {
            font-size: 16px;
        }

        .vote-button {
            display: block;
            width: 100%;
            margin-top: 20px;
            padding: 10px;
            font-size: 16px;
            text-align: center;
            background-color: #4caf50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .vote-button:hover {
            background-color: #45a049;
        }
    </style>
</head>

<body>
    <nav>
        <div class="logo">
            <h1>DataFlair Voting System</h1>
        </div>
        <div class="username">
            {% if user.is_authenticated %}
            <span>Welcome, {{ user.username }} <a href="{% url 'logout' %}">(logout)</a></span>
            {% endif %}
        </div>
    </nav>
    <br><br>
    {% for item in new_ques %}
    <div class="container">
        <form method="post" action="{% url 'votingpage' pk=item.pk %}">
            {% csrf_token %}
        <h2>{{ item.ques }}</h2>
            <button class="vote-button" type="submit">{% if vote.is_valid %} voted {% else %} vote {% endif %}</button>
        </form>
        <br>
    </div>
    {% endfor %}
   
</body>

</html>

Views.py 

from django.shortcuts import get_object_or_404, render, redirect, HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate, logout
from .models import Questions, Voted, UserProfile
from django.contrib import messages
# Create your views here.
def Index(request):
    return render(request, "app/login.html")

def register(request):
    return render(request, "app/registration.html")

@login_required(login_url="login")
def successfully(request):
    return render(request, "app/successfully_voted.html")

@login_required(login_url="login")
def already(request):
    return render(request, "app/already_voted.html")


def Registration(request):
    if request.method == "POST":
        username = request.POST['uname']
        email = request.POST['email']
        password = request.POST['passw']
        cpassword = request.POST['cpass']
        age = int(request.POST['age'])  # Convert age to an integer

        if password == cpassword:
            new_user = User.objects.create(
                username=username,
                email=email,
            )
            new_user.set_password(password)
            new_user.save()

            # Save the age information in the UserProfile model
            UserProfile.objects.create(user=new_user, age=age)

            return redirect("index")
        return render(request, "app/registration.html")
   
def Loginview(request):
    if request.method == "POST":
        username = request.POST['uname']
        password = request.POST['password']

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect("show")
        else:
            return HttpResponse("invalid credentials")
   
@login_required(login_url="login")
def home(request):
    return render(request, "app/votingpage.html")

@login_required(login_url="login")
def Voting(request, pk):
    user = request.user
    ques = get_object_or_404(Questions, pk=pk)
   
    # Check if the user is below 18 years old
    user_profile = UserProfile.objects.get(user=user)
    if user_profile.age < 18:
        messages.warning(request, "Voters below 18 years of age are not allowed to vote.")
        return render(request, "app/votingpage.html")

    # Check if the user has already voted for this question
    if Voted.objects.filter(user=user, voted_question=ques).exists():
        return redirect("successfully")
    else:
        ques.vote += 1
        ques.save()
        Voted.objects.create(user=user, voted_question=ques)
        return redirect('already')

@login_required(login_url="login")
def show(request):
    new_ques = Questions.objects.all()
   

    # Check if the user's age is less than 18 and show a warning message
    user_profile = UserProfile.objects.get(user=request.user)
    if user_profile.age < 18:
        messages.warning(request, "Voter below 18 age group is not allowed.")

    return render(request, "app/votingpage.html", {"new_ques": new_ques, "user_profile": user_profile})

def signout(request):
    logout(request)
    return redirect("index")

Urls.py

from django.urls import path,include
from . import views

urlpatterns = [
    path("", views.Index, name="index"),
    path("register", views.register, name="register"),
    path("registration", views.Registration, name="registration"),
    path("home", views.home, name="home"),
    path("login", views.Loginview, name="login"),
    path("votingpage/<int:pk>", views.Voting, name="votingpage"),
    path("showques", views.show, name="show"),
    path("logout", views.signout, name="logout"),
    path("successfully", views.successfully, name="successfully"),
    path("already", views.already, name="already")
]

Python Django Online Voting System Output

online voting system login output

online voting system registration output

online voting system project output

voting page below age 18

Admin panel

Now how would we add data, delete, and update to the user side? Let’s come to the django inbuilt admin panel. So here are the details of the same:

1. Once you have your Django project set up and have created your models, you can use the admin panel to add data easily. Follow these steps:
2. Run python manage.py createsuperuser to create an admin user who can access the admin panel. Start the development server using python manage.py runserver. Open your browser and go to the admin panel URL (usually http://127.0.0.1:8000/admin/) Log in using the superuser credentials you created.
3. Then, Go to admin.py and add the following thing as follows:

from django.contrib import admin
from .models import YourModelName
 
admin.site.register(YourModelName)

Note: To display the model on the admin panel, you need to follow the third point.

admin panel show question

total votes admin page

Summary:

The provided code represents a basic online voting system implemented using Django framework. It includes registration, login, and voting functionalities. Users can register, log in, view and vote on questions. The system ensures authentication, prevents duplicate votes, and tracks user activity.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *