
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境搭建
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - If 語句
- Python - If else
- Python - 巢狀 If
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - While 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅限關鍵字引數
- Python - 位置引數
- Python - 僅限位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 排序列表
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 排序陣列
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝器類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 執行緒連線
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路程式設計
- Python - 網路程式設計
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUI
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類的超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
使用 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. 檔案結構

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

輸出
在執行 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 manage.py runserver
伺服器執行後,在您的 Web 瀏覽器中以隱身標籤訪問 http://127.0.0.1:8000/,您將看到投票系統的登入頁面,您可以在其中檢視可用的投票、投票和檢查結果。

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

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

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

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

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

現在的最終結果:

總結
投票系統專案對於如何利用Django框架設計投票應用程式非常有用。它展示瞭如何應用Django的模型-檢視-模板(MVT)模式來開發一個基於網際網路的應用程式,用於檢視投票、投票和檢視結果。在這個專案中,可以學習Django的基礎知識,例如定義模型、對映URL、檢視函式和渲染模板。
結論
儘管如此,這個專案對於從零開始學習Django非常重要,尤其適合那些使用Django進行Web開發的新手。透過這個過程,可以學習建立Django專案的過程,以及在專案中建立和管理模型以構建成功的Web應用程式。投票系統專案是其他應用程式的良好基礎,並且在Django中進一步嘗試它很有趣。