Django2.2幫助文檔的第一個例子:一個簡易的投票系統—Prat3_4
- 2020 年 3 月 6 日
- 筆記
原文鏈接
https://docs.djangoproject.com/en/2.2/intro/tutorial01/
強烈推薦
- b站教學視頻 Django 2.0和Python快速入門 (更新完畢) 強烈推薦
開始搭建簡易投票系統
- 創建項目
django-admin startproject mysite
- 創建app
cd mysite django-admin startapp polls
- 在polls文件夾下新建一個urls.py,寫上如下代碼
from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), ]
- 在mysite文件夾下的urls.py文件夾下寫上代碼
from django.contrib import admin from django.urls import path from django.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('polls/',include('polls.urls')), ]
- 在polls文件夾下新建一個templates文件夾
- 在templates文件夾下新建一個index.html文件,在文件里寫些內容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>這是index頁面</title> </head> <body> <h1>這是index頁面</h1> </body> </html>
- 在mysite文件夾下的settings.py文件中添加模板文件夾的路徑
os.path.join(BASE_DIR,'polls/templates')
- 在polls文件夾下的views.py文件中添加代碼
from django.shortcuts import render # Create your views here. def index(request): return render(request,'index.html')
- 試着運行服務器
python manage.py runserver
返回結果

image.png
- 註冊app,在mysite文件夾下的settings.py文件中寫入
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls.apps.PollsConfig', ]
- 在polls文件夾下的models.py文件中寫入如下代碼
import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 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
- 遷移數據庫
python manage.py makemigrations polls python manage.py sqlmigrate polls 0001 python manage.py migrate
- 用shell添加問題
from polls.models import Choice, Question Question.objects.all() from django.utils import timezone q = Question(question_text="你的性別是?", pub_date=timezone.now()) q.save() q.choice_set.create(choice_text='男', votes=0) q.choice_set.create(choice_text='女', votes=0) q.choice_set.create(choice_text='不告訴你', votes=0) q = Question(question_text="你喜歡的運動是?", pub_date=timezone.now()) q.choice_set.create(choice_text='籃球', votes=0) q.choice_set.create(choice_text='足球', votes=0) q.choice_set.create(choice_text='排球', votes=0) q.choice_set.create(choice_text='不告訴你', votes=0) Question.objects.all() Choice.objects.all()
- 創建超級管理員用戶
python manage.py createsuperuser
依次輸入用戶名,郵箱,密碼
- 運行服務器
python manage.py runserver
訪問 http://127.0.0.1:8000/admin/ 結果

image.png
- 在polls文件夾下的admin.py文件中添加
from django.contrib import admin # Register your models here. from .models import Question admin.site.register(Question)
刷新,重新訪問http://127.0.0.1:8000/admin/
結果

image.png

image.png
- 更改views.py文件中的代碼
from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {"latest_question_list":latest_question_list} return render(request,'index.html',context= context) def detail(request,question_id): question = get_object_or_404(Question,pk=question_id) return render(request,'detail.html',context={'question':question})
- 更改polls文件夾下urls.py的代碼
from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('<int:question_id>/',views.detail,name="detail"), ]
- 更改index.html文件中的代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>這是index頁面</title> </head> <body> <h1>這是index頁面</h1> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{{ question.id }}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </body> </html>
- 在templates文件夾下新建文件detail.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>這是詳情頁面</title> </head> <body> <h1>這是詳情頁面</h1> <h2>{{ question.question_text }}</h2> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul> </body> </html>
結果

image.png

image.png
- 在polls文件夾下新建static文件夾,然後在這個文件夾下新建style.css文件
li a { color:green }
- 最終代碼 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>這是index頁面</title> </head> <body> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <h1>這是index頁面</h1> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{{ question.id }}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </body> </html>
detail.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>這是詳情頁面</title> </head> <body> <h1>這是詳情頁面</h1> <h2>{{ question.question_text }}</h2> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</labelfor> {% endfor %} <input type="submit" value="Vote"> </form> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul> </body> </html>
results.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>這是結果頁面</title> </head> <body> <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li> {% endfor %} </ul> <a href="{% url 'detail' question.id %}"> Vote again ?</a> </body> </html>
urls.py
from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('<int:question_id>/',views.detail,name="detail"), path('<int:question_id>/vote/',views.vote,name='vote'), path('<int:question_id>/results/',views.results,name="results"), ]
views.py
from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.http import Http404 from django.http import HttpResponseRedirect from django.urls import reverse from .models import Question # Create your views here. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {"latest_question_list":latest_question_list} return render(request,'index.html',context= context) def detail(request,question_id): try: question = get_object_or_404(Question,pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist!") return render(request,'detail.html',context={'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,'detail.html',context={'question':question, 'error_message':"You did not select a choice!"}) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('results',args=(question_id,))) def results(request,question_id): question = get_object_or_404(Question,pk=question_id) return render(request,'results.html',context={'question':question})
model.py
import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) 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
- 最終效果

image.png

image.png

image.png

image.png

image.png
至此這個例子就重複完了!