Part 3: Views and templates

====> Write your first view
$ edit polls\views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

$ edit polls\urls.py

from django.conf.urls import url

from . import views

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

$ edit mysite\urls.py

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

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

====> Writing more views
$ edit polls\views.py

# ...

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)

$ edit polls\urls.py

from django.conf.urls import url

from . import views

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

====> Write views that actually do something
$ edit 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([p.question_text for p in latest_question_list])
    return HttpResponse(output)

# Leave the rest of the views (detail, results, vote) unchanged

$ edit polls\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 %}

$ edit polls\views.py

from django.http import HttpResponse
from django.template import RequestContext, 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 = RequestContext(request, {
        'latest_question_list': latest_question_list,
    })
    return HttpResponse(template.render(context))

====> A shortcut: render()

$ edit 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)

====> Raising a 404 error
$ edit polls\views.py

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

$ edit polls\templates\polls\detail.html
{{ question }}

====> A shortcut: get_object_or_404()
$ edit 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})

====> Use the template system
$ edit 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>

====> Removing hardcoded URLs in templates
$ edit polls\templates\polls\detail.html

from: <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

to:   <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

====> Namespacing URL names
$ edit mysite\urls.py

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

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

$ edit polls\templates\polls\index.html

from: <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
to:   <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

django学习笔记(3)的更多相关文章

  1. Django 学习笔记之四 QuerySet常用方法

    QuerySet是一个可遍历结构,它本质上是一个给定的模型的对象列表,是有序的. 1.建立模型: 2.数据文件(test.txt) 3.文件数据入库(默认的sqlite3) 入库之前执行 数据库同步命 ...

  2. Django 学习笔记之三 数据库输入数据

    假设建立了django_blog项目,建立blog的app ,在models.py里面增加了Blog类,同步数据库,并且建立了对应的表.具体的参照Django 学习笔记之二的相关命令. 那么这篇主要介 ...

  3. Django学习笔记(五)—— 表单

    疯狂的暑假学习之  Django学习笔记(五)-- 表单 參考:<The Django Book> 第7章 1. HttpRequest对象的信息 request.path         ...

  4. Django学习笔记(三)—— 型号 model

    疯狂暑期学习 Django学习笔记(三)-- 型号 model 參考:<The Django Book> 第5章 1.setting.py 配置 DATABASES = { 'defaul ...

  5. Django 学习笔记(二)

    Django 第一个 Hello World 项目 经过上一篇的安装,我们已经拥有了Django 框架 1.选择项目默认存放的地址 默认地址是C:\Users\Lee,也就是进入cmd控制台的地址,创 ...

  6. Django 学习笔记(五)模板标签

    关于Django模板标签官方网址https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ 1.IF标签 Hello World/vi ...

  7. Django 学习笔记(四)模板变量

    关于Django模板变量官方网址:https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ 1.传入普通变量 在hello/Hell ...

  8. Django 学习笔记(三)模板导入

    本章内容是将一个html网页放进模板中,并运行服务器将其展现出来. 平台:windows平台下Liunx子系统 目前的目录: hello ├── manage.py ├── hello │ ├── _ ...

  9. Django 学习笔记(七)数据库基本操作(增查改删)

    一.前期准备工作,创建数据库以及数据表,详情点击<Django 学习笔记(六)MySQL配置> 1.创建一个项目 2.创建一个应用 3.更改settings.py 4.更改models.p ...

  10. Django 学习笔记(六)MySQL配置

    环境:Ubuntu16.4 工具:Python3.5 一.安装MySQL数据库 终端命令: sudo apt-get install mysql-server sudo apt-get install ...

随机推荐

  1. CentOS6.4 下安装 Apache2.4.16

    1.准备工作 1.1.yum安装部分工具 1)yum -y install vim 2)yum -y install wget 3)yum -y install gcc 4)yum -y instal ...

  2. 数据库对比:选择MariaDB还是MySQL?

    作者 | EverSQL 译者 | 无明 这篇文章的目的主要是比较 MySQL 和 MariaDB 之间的主要相似点和不同点.我们将从性能.安全性和主要功能方面对这两个数据库展开对比,并列出在选择数据 ...

  3. iOS8 生成二维码与条形码

    iOS8 生成二维码与条形码 效果图: 源码: // // ViewController.m // CodeCreator // // Created by YouXianMing on 15/3/1 ...

  4. 用以替换系统NSLog的YouXianMingLog

    用以替换系统NSLog的YouXianMingLog 这是本人自己使用并改良的用以替换系统NSLog的类,非常好用,以下是使用示例,现在开源出来并提供源码,好用的话顶一下吧^_^ 效果: YouXia ...

  5. Proxyee-down的下载与安装教程

    源代码在:GitHub_proxyee-down 为了节约读者的时间,我把需要的资源文件打包好,百度云链接在下面 Proxyee-down最新版为2.54(2018.8.9更新) 最新版下载地址:链接 ...

  6. 数据挖掘比赛优秀经验贴-收集ing

    (1)TOP5%Kaggler:如何在 Kaggle 首战中进入前 10% | 干货https://www.leiphone.com/news/201703/kCMQyffeP0qUgD9a.html ...

  7. Hyper-v 中 CentOS 连接外网之有线网卡

    一.打开虚拟机交换管理器,查看默认的虚拟交换机 如果不是内部网络,则需要新建一个虚拟交换机,新的交换机应该使用内部网络: 二.配置虚拟机使用的交换机.如果 “默认开关” 不是内部网络,需要使用自己新创 ...

  8. Deadline下:写论文的总结

    终于赶在了11月底截止的时刻提交上了导航年会的论文.三天加上两个半晚上差不多干完了80%的活,无论是否能够被录,这次的写作收获很大. 认识到了: 1. 读文献时,一定要带着问题,如果是我来做,我会怎么 ...

  9. mysql 注入基础知识

    (1)注入的分类---仁者见仁,智者见智. 下面这个是阿德玛表哥的一段话,个人认为分类已经是够全面了.理解不了跳过,当你完全看完整个学习过程后再回头看这段.能完全理解下面的这些每个分类,对每个分类有属 ...

  10. HTML、jsp页面中radio,checkbox,select数据回显功能,默认被选中问题

    最近常常遇到各种复选框.单选框.下拉框的默认被选中的问题,开始也是绞尽脑汁的想办法,今天写一篇学习总结的博文来写一下学习总结. 单选框(radio)默认被选中: 一.jstl技术进行回显 <in ...