使用 Django 框架的投票系統專案



投票系統專案是一個使用 Django 框架建立的小型 Web 應用程式,用於組織投票。這是一個移動應用程式,允許使用者瀏覽他們感興趣的投票並從提供的選項中投票,以及檢視投票結果。管理員介面允許建立、列出和刪除投票問題和選項,而無需使用者介面。此專案使開發人員非常清楚 Django 的作用,它如何管理模型,如何處理檢視,甚至如何呈現模板。

安裝

要啟動並執行投票系統專案,請按照以下安裝步驟操作:

1. 已安裝 Python 和 pip

  • 需要 Python 3.11 或更高版本。
  • pip 是 Python 包安裝程式

2. 安裝 Django

開啟您的終端命令以安裝 Django

pip install django

3. 設定 Django 專案

  • 開啟 VS code 併為您的專案建立一個新資料夾
  • 在您的終端中導航到此目錄並執行:
  • 程式碼:django-admin startproject voting_system

建立 Django 應用

1. 建立應用

導航到 voting_system 目錄

cd voting_system

建立一個名為 polls 的新應用:

python manage.py startapp polls

2. 定義模型:polls/models.py

from django.db import models
from django.utils import timezone

class Question(models.Model):
   question_text = models.CharField(max_length=200)
   pub_date = models.DateTimeField('date published')

   def __str__(self):
      return self.question_text

class Choice(models.Model):
   question = models.ForeignKey(Question, on_delete=models.CASCADE)
   choice_text = models.CharField(max_length=200)
   votes = models.IntegerField(default=0)

   def __str__(self):
      return self.choice_text

3. 應用遷移

轉到您的終端並編寫以下內容:

python manage.py makemigrations
python manage.py migrate

4. 檔案結構

File Structure

5. 在 polls/views.py 中建立檢視

from django.shortcuts import render, get_object_or_404
from .models import Question, Choice
from django.http import HttpResponse

def homepage(request):
   return HttpResponse("Welcome to the Voting System!")

def index(request):
   latest_question_list = Question.objects.order_by('-pub_date')[:5]
   context = {'latest_question_list': latest_question_list}
   return render(request, 'polls/index.html', context)

def detail(request, question_id):
   question = get_object_or_404(Question, pk=question_id)
   return render(request, 'polls/detail.html', {'question': question})

def results(request, question_id):
   question = get_object_or_404(Question, pk=question_id)
   return render(request, 'polls/results.html', {'question': question})

def vote(request, question_id):
   question = get_object_or_404(Question, pk=question_id)
   try:
      selected_choice = question.choice_set.get(pk=request.POST['choice'])
   except (KeyError, Choice.DoesNotExist):
      return render(request, 'polls/detail.html', {
         'question': question,
         'error_message': "You didn't select a choice.",
      })
   else:
      selected_choice.votes += 1
      selected_choice.save()
      return render(request, 'polls/results.html', {'question': question})

6. 在 polls/urls.py 中配置 URL

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
   path('', views.index, name='index'),
   path('question/<int:question_id>/', views.detail, name='detail'),
   path('question/<int:question_id>/results/', views.results, name='results'),
   path('question/<int:question_id>/vote/', views.vote, name='vote'),
   path('homepage/', views.homepage, name='homepage'),
]

7. 在 voting_system/urls.py 中更新專案 URL

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

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

8. 建立模板

基本模板 (polls/templates/polls/base.html)

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>{% block title %}Voting System{% endblock %}</title>
   <link rel="stylesheet" href="{% static 'polls/styles.css' %}">
</head>
<body>
<header>
<h1>Voting System</h1>
<nav>
<ul>
   <li><a href="{% url 'polls:index' %}">View Available Polls</a></li>
   <li><a href="{% url 'polls:homepage' %}">Home</a></li>
</ul>
</nav>
</header>
<main>
   {% block content %}{% endblock %}
</main>
</body>
</html>

索引模板 (polls/templates/polls/index.html)

{% extends 'polls/base.html' %}
{% block title %}Polls{% endblock %}
{% block content %}
<h2>Latest Polls</h2>
<ul>
   {% for question in latest_question_list %}
   <li>
      <a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a>
   </li>
   {% endfor %}
</ul>
{% endblock %}

詳情模板 (polls/templates/polls/detail.html)

{% extends 'polls/base.html' %}
{% block title %}Poll Details{% endblock %}
{% block content %}
<h2>{{ question.question_text }}</h2>
<form action="{% url 'polls:vote' question.id %}" method="post">
   {% csrf_token %}
   {% for choice in question.choice_set.all %}
   <input type="radio" id="choice{{ choice.id }}" name="choice" value="{{ choice.id }}">
   <label for="choice{{ choice.id }}">{{ choice.choice_text }}</label><br>
   {% endfor %}
   <input type="submit" value="Vote">
</form>
<p><a href="{% url 'polls:index' %}">Back to Polls</a></p>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
{% endblock %}

結果模板 (polls/templates/polls/results.html)

{% extends 'polls/base.html' %}
{% block title %}Poll Results{% endblock %}
{% block content %}
<h2>{{ question.question_text }}</h2>
<ul>
   {% for choice in question.choice_set.all %}
   <li>{{ choice.choice_text }}: {{ choice.votes }} votes</li>
   {% endfor %}
</ul>
<p><a href="{% url 'polls:index' %}">Back to Polls</a></p>
{% endblock %}

9. 建立靜態檔案

新增您的 CSS 檔案 (polls/static/polls/styles.css) 以設定應用程式的樣式。

示例

body {
   font-family: Arial, sans-serif;
   margin: 0;
   padding: 0;
   background-color: #f4f4f4;
}

header {
   background-color: #333;
   color: white;
   padding: 1rem;
   text-align: center;
}

nav ul {
   list-style: none;
   padding: 0;
}

nav ul li {
   display: inline;
   margin: 0 1rem;
}

nav ul li a {
   color: white;
   text-decoration: none;
}

main {
   padding: 1rem;
}

h2 {
   color: #333;
}

form {
   background-color: #fff;
   padding: 1rem;
   border-radius: 5px;
   box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

form input[type="submit"] {
   background-color: #333;
   color: white;
   border: none;
   padding: 0.5rem 1rem;
   border-radius: 5px;
   cursor: pointer;
}

10. admin.py 檔案

from django.contrib import admin
from .models import Question, Choice, Vote

class ChoiceInline(admin.TabularInline):
   model = Choice
   extra = 2  # Number of empty choice fields to display

class QuestionAdmin(admin.ModelAdmin):
   fieldsets = [
      (None, {'fields': ['question_text']}),
      ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}),
   ]
   inlines = [ChoiceInline]
   list_display = ('question_text', 'pub_date')
   list_filter = ['pub_date']
   search_fields = ['question_text']

class ChoiceAdmin(admin.ModelAdmin):
   list_display = ('choice_text', 'votes', 'question')
   list_filter = ['question']
   search_fields = ['choice_text']

class VoteAdmin(admin.ModelAdmin):
   list_display = ('voter_name', 'choice')
   list_filter = ['choice']
   search_fields = ['voter_name']

admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin)
admin.site.register(Vote, VoteAdmin)

11. settings.py

Django settings for voting_system project.

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

For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ahjvi2=3zf5j8+%71b6hpn+5!m0+hggf4+343(i8yp%qw^^d20'

# 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',
   'polls',
]

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 = 'voting_system.urls'

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 = 'voting_system.wsgi.application'

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

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

# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

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/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

12. 建立超級使用者

現在開啟您的終端並編寫以下程式碼:

python manage.py createsuperuser
Python Code

輸出

在執行 runserver 之前,您可以編寫此 **Python Shell**

您還可以使用 Django shell 與模型進行互動。以下是一個示例:

開啟 Django Shell

python manage.py shell

建立問題和選項

from polls.models import Question, Choice
from django.utils import timezone

# Create a new question
q = Question(question_text="What's your favorite color?", pub_date=timezone.now())
q.save()

# Add some choices to the question
q.choice_set.create(choice_text='Red', votes=0)
q.choice_set.create(choice_text='Blue', votes=0)
q.choice_set.create(choice_text='Green', votes=0)
q.choice_set.create(choice_text='Yellow', votes=0)

退出 Shell

exit()

檢視輸出:

Python Output

完成設定和程式碼實現後,您可以在您的視窗中編寫此程式碼以執行伺服器:

python manage.py runserver

伺服器執行後,在您的 Web 瀏覽器中以隱身標籤訪問 http://127.0.0.1:8000/,您將看到投票系統的登入頁面,您可以在其中檢視可用的投票、投票和檢查結果。

Python Output

搜尋後,此頁面將顯示在您的螢幕上:

Python Output

您可以新增更多問題,我們只添加了一個問題,點選問題:

Python Output

您必須填寫您的姓名,否則它將無法工作,您無法投票:

Python Output

然後點選投票選項,您將看到誰投了哪種顏色:

Python Output

您可以再次使用不同的使用者投票:

Python Output

現在的最終結果:

Python Output

總結

投票系統專案對於如何利用Django框架設計投票應用程式非常有用。它展示瞭如何應用Django的模型-檢視-模板(MVT)模式來開發一個基於網際網路的應用程式,用於檢視投票、投票和檢視結果。在這個專案中,可以學習Django的基礎知識,例如定義模型、對映URL、檢視函式和渲染模板。

結論

儘管如此,這個專案對於從零開始學習Django非常重要,尤其適合那些使用Django進行Web開發的新手。透過這個過程,可以學習建立Django專案的過程,以及在專案中建立和管理模型以構建成功的Web應用程式。投票系統專案是其他應用程式的良好基礎,並且在Django中進一步嘗試它很有趣。

python_projects_from_basic_to_advanced.htm
廣告