1. 程式人生 > >六、Django之表單和類視圖-Part 4

六、Django之表單和類視圖-Part 4

true abs 不能 註意 自動跳轉 請求偽造 mes direct base

一、表單form

為了接收用戶的投票選擇,我們需要在前端頁面顯示一個投票界面。讓我們重寫先前的polls/detail.html文件,代碼如下:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls: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 }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />

簡要說明:

  • 上面的模板顯示一系列單選按鈕,按鈕的值是選項的ID,按鈕的名字是字符串"choice"。這意味著,當你選擇了其中某個按鈕,並提交表單,一個包含數據choice=#的POST請求將被發送到指定的url,#是被選擇的選項的ID。這就是HTML表單的基本概念。
  • 如果你有一定的前端開發基礎,那麽form標簽的action屬性和method屬性你應該很清楚它們的含義,action表示你要發送的目的url,method表示提交數據的方式,一般分POST和GET。
  • forloop.counter是DJango模板系統專門提供的一個變量,用來表示你當前循環的次數,一般用來給循環項目添加有序數標。
  • 由於我們發送了一個POST請求,就必須考慮一個跨站請求偽造的安全問題,簡稱CSRF(具體含義請百度)。Django為你提供了一個簡單的方法來避免這個困擾,那就是在form表單內添加一條{% csrf_token %}標簽,標簽名不可更改,固定格式,位置任意,只要是在form表單內。這個方法對form表單的提交方式方便好使,但如果是用ajax的方式提交數據,那麽就不能用這個方法了。

現在,讓我們創建一個處理提交過來的數據的視圖。前面我們已經寫了一個“占坑”的vote視圖的url(polls/urls.py):

url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),

以及“占坑”的vote視圖函數(polls/views.py),我們把坑填起來:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from .models import Choice, 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):
        # 發生choice未找到異常時,重新返回表單頁面,並給出提示信息
        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 HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

有些新的東西,我們要解釋一下:

  • request.POST是一個類似字典的對象,允許你通過鍵名訪問提交的數據。本例中,request.POST[’choice’]返回被選擇選項的ID,並且值的類型永遠是string字符串,那怕它看起來像數字!同樣的,你也可以用類似的手段獲取GET請求發送過來的數據,一個道理。
  • request.POST[’choice’]有可能觸發一個KeyError異常,如果你的POST數據裏沒有提供choice鍵值,在這種情況下,上面的代碼會返回表單頁面並給出錯誤提示。PS:通常我們會給個默認值,防止這種異常的產生,例如request.POST[’choice’,None],一個None解決所有問題。
  • 在選擇計數器加一後,返回的是一個HttpResponseRedirect而不是先前我們常用的HttpResponse。HttpResponseRedirect需要一個參數:重定向的URL。這裏有一個建議,當你成功處理POST數據後,應當保持一個良好的習慣,始終返回一個HttpResponseRedirect。這不僅僅是對Django而言,它是一個良好的WEB開發習慣。
  • 我們在上面HttpResponseRedirect的構造器中使用了一個reverse()函數。它能幫助我們避免在視圖函數中硬編碼URL。它首先需要一個我們在URLconf中指定的name,然後是傳遞的數據。例如‘/polls/3/results/‘,其中的3是某個question.id的值。重定向後將進入polls:results對應的視圖,並將question.id傳遞給它。白話來講,就是把活扔給另外一個路由對應的視圖去幹。

當有人對某個問題投票後,vote()視圖重定向到了問卷的結果顯示頁面。下面我們來寫這個處理結果頁面的視圖(polls/views.py):

from django.shortcuts import get_object_or_404, render

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

同樣,還需要寫個模板polls/templates/polls/results.html。(路由、視圖、模板、模型!都是這個套路....)

<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 'polls:detail' question.id %}">Vote again?</a>

現在你可以到瀏覽器中訪問/polls/1/了,投票吧。你會看到一個結果頁面,每投一次,它的內容就更新一次。如果你提交的時候沒有選擇項目,則會得到一個錯誤提示。

如果你在前面漏掉了一部分操作沒做,比如沒有創建choice選項對象,那麽可以按下面的操作,補充一下:

F:\Django_course\mysite>python manage.py shell
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Question
>>> q = Question.objects.get(pk=1)
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Choice object>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: Choice object>
>>> q.choice_set.create(choice_text='Just hacking again', votes=0)
<Choice: Choice object>

為了方便大家,我將當前狀態下的各主要文件內容一並貼出,供大家對照參考!

1--完整的mysite/urls.py文件如下:

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^polls/', include('polls.urls')),
]

2--完整的mysite/settings.py文件如下:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '85vvuta(p05ow!4pz2b0qbduu0%pq6x5q66-ei*pg+-lbdr#m^'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True

3--完整的polls/views.py應該如下所示:

from django.shortcuts import reverse
from django.shortcuts import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.shortcuts import HttpResponse
from django.shortcuts import render
from .models import Choice
from .models import Question
from django.template import loader
# Create your views here.


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


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 HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

4--完整的polls/urls.py應該如下所示:

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

app_name = 'polls'

urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    # ex: /polls/5/
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

5--完整的polls/model.py文件如下:

from django.db import models
import datetime
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 was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    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

6--完整的polls/admin.py文件如下:

from django.contrib import admin

# Register your models here.

from .models import Question

admin.site.register(Question)

7--完整的templates/polls/index.html文件如下:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

8--完整的templates/polls/detail.html文件如下:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls: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 }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

9--完整的templates/polls/results.html文件如下:

<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 'polls:detail' question.id %}">Vote again?</a>

vote()視圖沒有對應的html模板,它直接跳轉到results視圖去了。

運行服務器,測試各功能:

這是問卷列表頁面:

技術分享圖片

這是“what‘s up”問卷選項頁面:

技術分享圖片

這是選擇結果頁面:

技術分享圖片

這是沒有選擇選項時,提示錯誤信息的頁面:

技術分享圖片

二、 使用類視圖:減少重復代碼

上面的detail、index和results視圖的代碼非常相似,有點冗余,這是一個程序猿不能忍受的。他們都具有類似的業務邏輯,實現類似的功能:通過從URL傳遞過來的參數去數據庫查詢數據,加載一個模板,利用剛才的數據渲染模板,返回這個模板。由於這個過程是如此的常見,Django很善解人意的幫你想辦法偷懶,於是它提供了一種快捷方式,名為“類視圖”。

現在,讓我們來試試看將原來的代碼改為使用類視圖的方式,整個過程分三步走:

  • 修改URLconf設置
  • 刪除一些舊的無用的視圖
  • 采用基於類視圖的新視圖
    PS:為什麽本教程的代碼來回改動這麽頻繁?

答:通常在寫一個Django的app時,我們一開始就要決定使用類視圖還是不用,而不是等到代碼寫到一半了才重構你的代碼成類視圖。但是本教程為了讓你清晰的理解視圖的內涵,“故意”走了一條比較曲折的路,因為我們的哲學是在你使用計算器之前你得先知道基本的數學公式。

1.改良URLconf

打開polls/urls.py文件,將其修改成下面的樣子:

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

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

ps: 將原來的修改成了.

2.修改視圖

接下來,打開polls/views.py文件,刪掉index、detail和results視圖,替換成Django的類視圖,如下所示:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from .models import Choice, Question


class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'
    def get_queryset(self):
    """返回最近發布的5個問卷."""
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Question
    template_name ='polls/results.html'


def vote(request, question_id):
... # 這個視圖未改變!!!

在這裏,我們使用了兩種類視圖ListView和DetailView(它們是作為父類被繼承的)。這兩者分別代表“顯示一個對象的列表”和“顯示特定類型對象的詳細頁面”的抽象概念。

  • 每一種類視圖都需要知道它要作用在哪個模型上,這通過model屬性提供。

  • DetailView類視圖需要從url捕獲到的稱為"pk"的主鍵值,因此我們在url文件中將2和3條目的修改成了

默認情況下,DetailView類視圖使用一個稱作/_detail.html的模板。在本例中,實際使用的是polls/detail.html。template_name屬性就是用來指定這個模板名的,用於代替自動生成的默認模板名。(一定要仔細觀察上面的代碼,對號入座,註意細節。)同樣的,在resutls列表視圖中,指定template_name為‘polls/results.html‘,這樣就確保了雖然resulst視圖和detail視圖同樣繼承了DetailView類,使用了同樣的model:Qeustion,但它們依然會顯示不同的頁面。(模板不同嘛!so easy!)

類似的,ListView類視圖使用一個默認模板稱為/_list.html。我們也使用template_name這個變量來告訴ListView使用我們已經存在的 "polls/index.html"模板,而不是使用它自己默認的那個。

在教程的前面部分,我們給模板提供了一個包含question和latest_question_list的上下文變量。而對於DetailView,question變量會被自動提供,因為我們使用了Django的模型(Question),Django會智能的選擇合適的上下文變量。然而,對於ListView,自動生成的上下文變量是question_list。為了覆蓋它,我們提供了context_object_name屬性,指定說我們希望使用latest_question_list而不是question_list。

六、Django之表單和類視圖-Part 4