【Web開發二】Django框架中部署一套投票網站

Django原理,URLS路由接收到客戶端訪問的請求------>view視圖函數進行請求的處理-------->models模型(數據庫)進行數據的處理--------->view視圖函數進行數據的處理--------->template模板(HTML)進行數據的展示,反饋給客戶端

一、初始化數據庫,生成管理後臺的用戶。登錄管理後臺

python manage.py migrate       #初始化數據庫

python manage.py createsuperuser      #創建超級用戶

二、創建模型,模型,也就是關聯到數據庫的類函數,例如投票系統,那麼就有投票項,投票項創建時間,投票內容選項,投票內容選項創建時間,票數。遵從數據庫的準則,我們把投票項,和投票內容選項分開在兩個表。

打開models.py

from django.db import models

# Create your models here.
class Question(models.Model):                                        #創建這樣類,繼承於父類
    question_text = models.CharField(max_length=200)   #創建實例,類型爲字符,最大長度200
    publish_date = models.DateTimeField('publish date')  #創建實例,類型爲時間,聲明爲xxxx
    
    def __str__(self):                                                           使用str方法,返回問題內容
        return self.question_text

class Choice(models.Model):                                            #創建這樣類,繼承於父類
    choice_text = models.CharField(max_length=100)       #創建實例,類型爲字符,最大長度100
    publish_date = models.DateTimeField('publish date')   #創建實例,類型爲時間,聲明爲xxxx
    vote = models.IntegerField(default=0)                           #創建實例,類型爲數字,默認爲0
    question = models.ForeignKey(Question, on_delete=models.CASCADE) #創建實例,類型爲(Question)外鍵,刪除關聯
    
    def __str__(self):                                                             使用str方法,返回問題選項內容
        return self.choice_text

三、把應用添加到項目裏面,把模型註冊到後臺管理。並且優化管理後臺。

1、打開settings.py

2、打開admin.py

from django.contrib import admin
from .models import Question, Choice                                     #導入模塊
class QuestionAdmin(admin.ModelAdmin):                              #新建模型,集成於父類
    list_display = ('question_text', 'publish_date')                       #優化後臺管理器顯示
    list_filter = ('publish_date',)                                                    #使用時間作爲過濾器
    search_fields = ('question_text',)                                           #使用內容作爲搜索器
    ordering = ('-publish_date', 'question_text')                           #使用降序時間排序,使用問題排序
    date_hierarchy = 'publish_date'                                             #使用時間作爲時間軸

class ChoiceAdmin(admin.ModelAdmin):
    list_display = ('question', 'choice_text', 'vote', 'publish_date')
    list_filter = ('publish_date',)
    search_fields = ('choice_text',)
    ordering = ('-publish_date', 'vote')
    date_hierarchy = 'publish_date'
    raw_id_fields = ('question',)                                                     #優化選項,效果是顯示question詳情

admin.site.register(Question, QuestionAdmin)                            #註冊到管理後臺
admin.site.register(Choice, ChoiceAdmin)

3、效果如圖

4、我們都說了,模型就是關聯到數據庫的。現在模型有了。那麼就應該把模型。應用到數據庫上,讓數據庫生成模型裏面的字段。

python manage.py makemigrations         #生成數據庫語句

python manage.py migrate                       #執行語句

三、在web頁面創建問題和相關選項。

生成問題

生成對應問題的選項

四、查看數據庫,可以得到,polls_question和polls_choice這2個表格,有了剛剛我們輸入的內容了。並且,Django自動爲他們加入了id主鍵。並且choice表格裏面有外鍵約束。

五、製作主頁,走一遍Django的工作原理

根據Django的工作原理,我們第一步要修改的,應該是應用的urls文件

1、打開urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

這裏已經寫好去index的路由了。交友view裏面的index函數處理。

2、打開views.py

from django.shortcuts import render, HttpResponse
from .models import Question, Choice                                          #導入模塊

# Create your views here.
def index(request):                                                                         #創建index函數
    question = Question.objects.all()                                                #定義實例question,值爲Question的對象查詢集合
    return render(request, 'polls/index.html', {'question': question}) #發送數據到polls下的index.html,參數名爲question,值爲question

3、創建模板目錄,創建模板文件

mkdir -p  polls/templates/polls

4、編寫index.html文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>polls主頁</title>
</head>
<body>
<ul>
    {% for q in question %}
    <li>
        <a href="此處填寫的是超鏈接跳轉的頁面,暫時留空">
            {{ q.question_text }}
        </a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ q.publish_date }}
    </li>
    {% endfor%}
</ul>
</body>
</html>

效果如圖

六、製作每個問題的詳情頁,實現訪問主頁,並且會進行跳轉。

1、慣例修改urls文件。

打開urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'(?P<question_id>\d+)/$', views.detail, name='detail') ###規劃url,我們用數字來做一個變量。然後根據數字來匹配polls_question的id,實現準確的定位到question_text。
]

2、修改views.py文件。新增detail視圖函數,獲取數據,然後發送給模板文件。

def detail(request, question_id):                                                        #question_id是從url這裏獲取的
    question = Question.objects.get(id=question_id)                          #通過get的方法,獲得對應的question實例
    return render(request, 'polls/detail.html', {'question': question})

3、創建detail.html文件,然後根據實際需求,編寫對應的視圖界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>投票詳情頁</title>
</head>
<body>
<p>{{ question }}</p>
<form action="此處留空,作用是提交數據到vote的">
    {% for c in question.choice_set.all %}
        <input type="radio" name="c_id" value="{{c.id}}">{{ c.choice_text }}       ##name和value處,後面會說明
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>

4、修改主頁index.html,爲超鏈接匹配detail.tml的模板

打開index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>polls主頁</title>
</head>
<body>
<ul>
    {% for q in question %}
    <li>
        <a href="{% url 'detail' question_id=q.id %}">    #調用url模塊,匹配detail視圖函數,作爲參數的question。值爲q.id
            {{ q.question_text }}
        </a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ q.publish_date }}
    </li>
    {% endfor%}
</ul>
</body>
</html>

到此,我們實現了。超鏈接跳轉的問題了。

七、製作投票結果的工作

1、urls.py文件新增記錄

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'(?P<question_id>\d+)/$', views.detail, name='detail'),
    url(r'(?P<question_id>\d+)/result/$', views.result, name='result'),   #新增
]

2、新增views.py文件中的函數

def result(request, question_id):
    question = Question.objects.get(id=question_id)
    return render(request, 'polls/result.html', {'question': question})

3、新增模板中的result.html文件,根據實際需求規劃好數據

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>投票結果頁</title>
</head>
<body>
<table border="1px">
    <tr>
        <td colspan="2">{{ question }}</td>
    </tr>
    {% for c in question.choice_set.all %}
    <tr>
        <td>
            {{ c.choice_text }}
        </td>
        <td>
            票數:{{ c.vote }}
        </td>
    </tr>
    {% endfor %}
</table>
</body>
</html>

效果如圖

八、創建投票的程序,思路應該是這樣的,在主頁中,選擇哪個問題,就相當於用question_id,打開對應的詳情頁,然後在詳情頁裏面,選擇哪個選項,選項的id會從表單中post到vote的程序。vote程序對數據進行+1,進行投票。然後投票結束後反饋結果頁面給客戶端。我們先做detail主頁的代碼,然後再完善投票程序。

1、

1、新增urls.py文件的代碼

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'(?P<question_id>\d+)/$', views.detail, name='detail'),
    url(r'(?P<question_id>\d+)/result/$', views.result, name='result'),
    url(r'(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
]

2、新增views.py文件記錄。

def vote(request, question_id):                                   #創建vote程序,參數question_id是從detail中獲取
    choice_id = request.POST.get('c_id')                      #利用request的方法,獲取參數c_id
    c = Choice.objects.get(id=choice_id)                      #獲取到Choice的實例
    c.vote += 1                                                               #票數+1
    c.save()
    return redirect('result', question_id=question_id)     #重定向到result頁面。

3、修改detail.py文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>投票詳情頁</title>
</head>
<body>
<p>{{ question }}</p>
<form action="{% url 'vote' question_id=question.id %}" method="post">    #方式爲post,然後提交數據到vote,參數爲XXXXX
    {% for c in question.choice_set.all %}
        <input type="radio" name="c_id" value="{{ c.id }}">{{ c.choice_text }}
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

基本完成

效果如下

css樣式,bootstrap樣式,返回首頁等等都可以添加。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章