django shortcuts 详解

 

django中为了方便web的开发、定义了许多有用的shortcut 。由于shortcut带来的方便用文字描述是有点苍白的、所以在这里打算用一些例子来说明

 

一、一个hello world 的例子:

我们用low B 的方式实现一个功能,这个功能就是当用户打开页面的时候,向用户显示一句 "hello xxx"

比如我们在url中给出的名字是welson

如果 low B 的实现这个功能 view的代码如下:

from django.shortcuts import render
from django.http import HttpRequest,HttpResponse,HttpResponseRedirect
# Create your views here.

from django.shortcuts import render


def index(request,name='world'):
    html_str="""
    <html>
        <head>
            <title> hello page </title>
        </head>

        <body>
            <p>
                hello {0}
            </p>
        </body>
    </html>
    """.format(name)
    return HttpResponse(html_str)

 

注册url于view的关联(polls.urls.py):

from django.contrib import admin
from django.urls import path
from .views import index

urlpatterns = [
    path('<str:name>/', index),
]

 

根url配置如下:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
]

 

 这种low B 的方式有什么问题:

 

   1、由于html代码与python代码混合在一起、不方便更改;就是给web加一个样式,也是非常困难的,鬼知道你是不是哪个view中

  的html代码没有加入新的样式。

 

二、用template 来提升B格:

 

创建template文件来,分离html与python

polls/templates/polls/index-template.html的内容如下:

<html>
    <head>
        <title>this is index template</title>
    </head>

    <body>
        <p>
            {{ name }}
        </p>
    </body>
</html>

 

新的view代码就可以这样写了:

from django.shortcuts import render
from django.http import HttpRequest,HttpResponse,HttpResponseRedirect
# Create your views here.


def index(request,name='world'):
    return render(request,template_name='polls/index-template.html',context={'name': name})

 

 

 

 

 

 

----

posted on 2018-02-28 10:41  蒋乐兴的技术随笔  阅读(1521)  评论(0编辑  收藏  举报

导航