django学习笔记(3)

简介: Part 3: Views and templates====> Write your first view$ edit polls\views.pyfrom django.http import HttpResponsedef index(request):    return HttpResponse("Hello, world.

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>





目录
相关文章
|
5月前
|
Python
基于Django的Python应用—学习笔记—功能完善
基于Django的Python应用—学习笔记—功能完善
|
5月前
|
存储 数据库 数据安全/隐私保护
基于Django的Python应用——学习笔记
基于Django的Python应用——学习笔记
|
安全 中间件 开发者
【Django学习笔记 - 9】:装饰器在类视图中的使用、中间件(开发中间件)、知识点小补充(子应用的集中管理)
【Django学习笔记 - 9】:装饰器在类视图中的使用、中间件(开发中间件)、知识点小补充(子应用的集中管理)
358 2
【Django学习笔记 - 9】:装饰器在类视图中的使用、中间件(开发中间件)、知识点小补充(子应用的集中管理)
|
数据库 数据安全/隐私保护 Python
【Django学习笔记 - 19】:认证、自定义认证、权限、限流
【Django学习笔记 - 19】:认证、自定义认证、权限、限流
266 0
【Django学习笔记 - 19】:认证、自定义认证、权限、限流
|
缓存 前端开发 数据库
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由2
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
156 0
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由2
|
XML JSON 前端开发
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
203 0
【Django学习笔记 - 18】:drf请求响应简介、基类(APIView、GenericAPIView)、mixin扩展类与三级视图、视图集与路由
|
XML JSON 前端开发
【Django学习笔记 - 17】:序列化和反序列化(restful接口小案例、DRF的工程搭建、序列化器与序列化、验证、保存)
【Django学习笔记 - 17】:序列化和反序列化(restful接口小案例、DRF的工程搭建、序列化器与序列化、验证、保存)
516 0
【Django学习笔记 - 17】:序列化和反序列化(restful接口小案例、DRF的工程搭建、序列化器与序列化、验证、保存)
|
JSON 前端开发 JavaScript
【Django学习笔记 - 16】:DRF概述、Web应用模式(前后端分离简介)
【Django学习笔记 - 16】:DRF概述、Web应用模式(前后端分离简介)
286 0
【Django学习笔记 - 16】:DRF概述、Web应用模式(前后端分离简介)
|
Python
【Django学习笔记 - 15】:admin站点编辑(关联对象在列表页中添加,编辑页调整、图片设置)2
【Django学习笔记 - 15】:admin站点编辑(关联对象在列表页中添加,编辑页调整、图片设置)
【Django学习笔记 - 15】:admin站点编辑(关联对象在列表页中添加,编辑页调整、图片设置)2