Part 4:表單和類視圖--Django從入門到精通系列教程


該系列教程系我的原創,並完整發布在我的官網劉江的博客和教程

全部轉載本文者,需在頂部顯著位置註明原做者及www.liujiangblog.com官網地址。


1、表單form

爲了接收用戶的投票選擇,咱們須要在前端頁面顯示一個投票界面。讓咱們重寫先前的polls/detail.html文件,代碼以下: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>

簡要說明:前端

  • 上面的模板顯示一系列單選按鈕,按鈕的值是選項的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):python

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

以及「佔坑」的vote視圖函數(polls/views.py),咱們把坑填起來:ajax

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,)))

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

  • 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):shell

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/了,投票吧。你會看到一個結果頁面,每投一次,它的內容就更新一次。若是你提交的時候沒有選擇項目,則會獲得一個錯誤提示。django

若是你在前面漏掉了一部分操做沒作,好比沒有建立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視圖去了。

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

這是問卷列表頁面:

image.png-13kB

這是「what's up」問卷選項頁面:

image.png-23.9kB

這是選擇結果頁面:

image.png-26.2kB

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

image.png-28.4kB

請你們對比參考上面的內容,看看你本身的結果是否同樣。

2、 使用類視圖:減小重複代碼

上面的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'),
]

請注意:在上面的的第2,3條目中將原來的<question_id>修改爲了<pk>.

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):
... # 這個視圖未改變!!!

在這裏,咱們使用了兩種類視圖ListViewDetailView(它們是做爲父類被繼承的)。這二者分別表明「顯示一個對象的列表」和「顯示特定類型對象的詳細頁面」的抽象概念。

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

  • DetailView類視圖須要從url捕獲到的稱爲"pk"的主鍵值,所以咱們在url文件中將2和3條目的<question_id>修改爲了<pk>

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

相似的,ListView類視圖使用一個默認模板稱爲<app name>/<model name>_list.html。咱們也使用template_name這個變量來告訴ListView使用咱們已經存在的
"polls/index.html"模板,而不是使用它本身默認的那個。

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

如今能夠運行開發服務器,而後試試基於類視圖的應用程序了。類視圖是Django比較高級的一種用法,初學可能不太好理解,不要緊,咱們先有個印象。

相關文章
相關標籤/搜索