04 - Views and templates

Views and templates

  1. Writing more views

    # polls/views.py 
    # views response
    def detail(request, question_id):
        return HttpResponse("You're looking at question %s." % question_id)
    
    def results(request, question_id):
        response = "You're looking at the results of question %s."
        return HttpResponse(response % question_id)
    
    def vote(request, question_id):
        return HttpResponse("You're voting on question %s." % question_id)
    
    # polls/urls.py
    # adding the following path calls
    from django.urls import path
    from . import views
    
    urlpatterns = [
        # ex: /polls/
        path('', views.index, name='index'),
        # ex: /polls/5/
        path('<int:question_id>/', views.detail, name='detail'),
        # ex: /polls/5/results/
        path('<int:question_id>/results/', views.results, name='results'),
        # ex: /polls/5/vote/
        path('<int:question_id>/vote/', views.vote, name='vote'),
    ]
    
  2. Write views that actually do something

    # polls/views.py
    from django.http import HttpResponse
    from .models import Question
    
    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        output = ', '.join([q.question_text for q in latest_question_list])
        return HttpResponse(output)
    
    # Leave the rest of the views (detail, results, vote) unchanged
    
    # polls/templates/polls/index.html
    # Put the following code in that template
    {% 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 %}
    
    # polls/views.py
    # update our index view in polls/views.py to use the template
    from django.http import HttpResponse
    from django.template import loader
    from .models import Question
    
    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))
    
  3. A Shortcut function: render()

    # polls/views.py
    from django.shortcuts import render
    from .models import Question
    
    def index(request):
        latest_question_list = Question.objects.order_by('-pub_date')[:5]
        context = {'latest_question_list': latest_question_list}
        return render(request, 'polls/index.html', context)
    
  4. A shortcut function: get_object_or_404()

    # polls/views.py
    # Raising a 404 error
    from django.http import Http404
    from django.shortcuts import render
    
    from .models import Question
    # ...
    def detail(request, question_id):
        try:
            question = Question.objects.get(pk=question_id)
        except Question.DoesNotExist:
            raise Http404("Question does not exist")
        return render(request, 'polls/detail.html', {'question': question})
    
    <!-- polls/templates/polls/detail.html -->
    {{ question }}
    
    # polls/views.py
    from django.shortcuts import get_object_or_404, render
    from .models import Question
    # ...
    def detail(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        return render(request, 'polls/detail.html', {'question': question})
    
  5. Use the template system

    <!-- polls/templates/polls/detail.html -->
    <h1>{{ question.question_text }}</h1>
    <ul>
    {% for choice in question.choice_set.all %}
        <li>{{ choice.choice_text }}</li>
    {% endfor %}
    </ul>
    
  6. Removing hardcoded URLs in templates

    <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li></pre>    
    
    # the 'name' value as called by the {% url %} template tag
    path('<int:question_id>/', views.detail, name='detail'),
    # added the word 'specifics'
    path('specifics/<int:question_id>/', views.detail, name='detail'),
    
  7. Namespacing URL names

    # polls/urls.py
    from django.urls import path
    from . import views
    
    app_name = 'polls'
    urlpatterns = [
        path('', views.index, name='index'),
        path('<int:question_id>/', views.detail, name='detail'),
        path('<int:question_id>/results/', views.results, name='results'),
        path('<int:question_id>/vote/', views.vote, name='vote'),
    ]
    
    polls/templates/polls/index.html
    <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
    to point at the namespaced detail view:
    
    polls/templates/polls/index.html
    <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末庐完,一起剝皮案震驚了整個(gè)濱河市鉴未,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌遍膜,老刑警劉巖刻获,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绢要,死亡現(xiàn)場離奇詭異屿衅,居然都是意外死亡九昧,警方通過查閱死者的電腦和手機(jī)尉咕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門污朽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人龙考,你說我怎么就攤上這事蟆肆。” “怎么了晦款?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵炎功,是天一觀的道長。 經(jīng)常有香客問我缓溅,道長蛇损,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任坛怪,我火速辦了婚禮淤齐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘袜匿。我一直安慰自己更啄,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布居灯。 她就那樣靜靜地躺著祭务,像睡著了一般。 火紅的嫁衣襯著肌膚如雪怪嫌。 梳的紋絲不亂的頭發(fā)上义锥,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天,我揣著相機(jī)與錄音岩灭,去河邊找鬼拌倍。 笑死,一個(gè)胖子當(dāng)著我的面吹牛噪径,可吹牛的內(nèi)容都是我干的柱恤。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼熄云,長吁一口氣:“原來是場噩夢啊……” “哼膨更!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起缴允,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后练般,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體矗漾,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年薄料,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了敞贡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡摄职,死狀恐怖誊役,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情谷市,我是刑警寧澤蛔垢,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站迫悠,受9級特大地震影響鹏漆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜创泄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一艺玲、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鞠抑,春花似錦饭聚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至感混,卻和暖如春端幼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背弧满。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工婆跑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人庭呜。 一個(gè)月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓滑进,卻偏偏與公主長得像,于是被迫代替她去往敵國和親募谎。 傳聞我的和親對象是個(gè)殘疾皇子扶关,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容