美文网首页
Django -- Polls - Part 3

Django -- Polls - Part 3

作者: liaozb1996 | 来源:发表于2018-03-20 20:08 被阅读0次

URL dispatcher

View 视图

通过Python函数(或一个类的方法)来生成一个页面;可能会涉及通过Database API访问数据库;通过模板渲染页面;处理请求中的GET,POST;

视图最终将返回:HttpResponse 或 异常 (Http404

mysite/settings.py

创建视图

视图 Index

# polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Question

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

# 复杂的实现
# 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))

创建模板

# polls/templates/polls/index.html

{% if lastest_question_list %}
<ul>
    {% for question in lastest_question_list %}
    <li>
        <a href="{{ question.id }}">{{ question.question_text }}</a>
    </li>
    {% endfor %}
{% else %}
    <p>No Question!</p>
{% endif %}

模板的路径为 polls/templates/polls/index.html,第二个 /polls 为模板创建命名空间;

settings.pyAPP_DIR: True Django 会在APP目录下寻找模板


视图 detail

# polls/views.py
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

# 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>

django.shortcuts:Django 的设计原则就是要让各部分松耦合,每部分只做好其工作
get() -- get_object_or_404()
filter() -- get_list_or_404()

template guide


URL 软编码

polls/urls.py polls/templates/polls/detail.html

相关文章

  • Django -- Polls - Part 3

    URL dispatcher View 视图 通过Python函数(或一个类的方法)来生成一个页面;可能会涉及通过...

  • Django -- Polls - Part 2

    数据库配置 创建 Model Django Admin 本节包含的内容较多:Polls - Part 2 数据库配...

  • Django -- Polls - Part 4

    Form 如果是从服务器获取信息,使用 GET;如果是要从服务器修改信息,使用 POST;发生敏感信息,使用 PO...

  • Django -- Polls - Part 1

    创建项目结构 创建 APP -- Polls 结构 创建视图 View 配置/声明 URL -- URLconf ...

  • Django -- Polls - Part 7

    定制 Django Admin 步骤: 创建 admin.ModelAdmin 将子类作为 admin.site....

  • Django -- Polls - Part 6

    Django 渲染一个页面所需的图片,CSS, Javascript 称为静态文件 CSS 在APP下创建目录:p...

  • Django study

    [TOC] Django study creating a project 调试 demo-the Polls a...

  • django入门基础指令

    安装django指令 新建项目(名称为mysite) 运行django项目 创建应用(名称为polls) 为应用生...

  • 第一个Django App(六)

    静态文件 django.contrib.staticfiles 定制app的外观 在polls下创建static目...

  • Django学习(3)--管理站点

    编辑polls下面的admin.py进行站点管理。 加入了Question: from django.contri...

网友评论

      本文标题:Django -- Polls - Part 3

      本文链接:https://www.haomeiwen.com/subject/nvpbqftx.html