05 - Forms and generic views

Forms and generic views

  1. Write a simple form

    <!-- polls/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>
    
    # polls/urls.py
    path('<int:question_id>/vote/', views.vote, name='vote'),
    
    # polls/views.py
    from django.http import HttpResponse, HttpResponseRedirect
    from django.shortcuts import get_object_or_404, render
    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):
            # Redisplay the question voting form.
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
            })
        else:
            selected_choice.votes += 1
            selected_choice.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
    
    # 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>
    
  2. Use generic views: Less code is better

    # Amend URLconf
    polls/urls.py
    from django.urls import path
    
    from . import views
    
    app_name = 'polls'
    urlpatterns = [
        path('', views.IndexView.as_view(), name='index'),
        path('<int:pk>/', views.DetailView.as_view(), name='detail'),
        path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
        path('<int:question_id>/vote/', views.vote, name='vote'),
    ]
    
    # Amend views
    # polls/views.py
    from django.http import HttpResponseRedirect
    from django.shortcuts import get_object_or_404, render
    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):
            """Return the last five published questions."""
            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):
        ... # same as above, no changes needed.
    
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌而姐,老刑警劉巖挟裂,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件践剂,死亡現(xiàn)場離奇詭異越败,居然都是意外死亡驱显,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進店門放接,熙熙樓的掌柜王于貴愁眉苦臉地迎上來刺啦,“玉大人,你說我怎么就攤上這事纠脾÷耆常” “怎么了?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵苟蹈,是天一觀的道長糊渊。 經(jīng)常有香客問我,道長慧脱,這世上最難降的妖魔是什么渺绒? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮磷瘤,結果婚禮上芒篷,老公的妹妹穿的比我還像新娘搜变。我一直安慰自己采缚,他們只是感情好,可當我...
    茶點故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布挠他。 她就那樣靜靜地躺著扳抽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪殖侵。 梳的紋絲不亂的頭發(fā)上贸呢,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天,我揣著相機與錄音拢军,去河邊找鬼楞陷。 笑死,一個胖子當著我的面吹牛茉唉,可吹牛的內容都是我干的固蛾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼度陆,長吁一口氣:“原來是場噩夢啊……” “哼艾凯!你這毒婦竟也來了?” 一聲冷哼從身側響起懂傀,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤趾诗,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后蹬蚁,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體恃泪,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡郑兴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了贝乎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片杈笔。...
    茶點故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖糕非,靈堂內的尸體忽然破棺而出蒙具,到底是詐尸還是另有隱情,我是刑警寧澤朽肥,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布禁筏,位于F島的核電站,受9級特大地震影響衡招,放射性物質發(fā)生泄漏篱昔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一始腾、第九天 我趴在偏房一處隱蔽的房頂上張望州刽。 院中可真熱鬧,春花似錦浪箭、人聲如沸穗椅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽匹表。三九已至,卻和暖如春宣鄙,著一層夾襖步出監(jiān)牢的瞬間袍镀,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工冻晤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留苇羡,地道東北人。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓鼻弧,卻偏偏與公主長得像设江,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子温数,可洞房花燭夜當晚...
    茶點故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內容