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

 

 

 

 

 

 

----

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值