美文网首页
Python实战计划week4_0_3项目

Python实战计划week4_0_3项目

作者: 乐小Pi孩_VoV | 来源:发表于2016-08-10 10:42 被阅读21次

在前面,我们学习了:
1.创建一个虚拟环境

D:\vir>virtualenv your_name
#或者
D:\vir>python -m venv your_name

2.进入虚拟环境中

D:\vir>your_name\Scripts\activate

3.在虚拟环境中新建Django项目

(your_name) D:\vir>cd your_name
(your_name) D:\vir\your_name>python django-admin.py startproject your_django_item
#创建了一个名为your_django_item的django项目

4.在Django项目中创建Django App

(your_name) D:\vir\your_name\your_django_item>python manage.py startapp your_app

5.用runserver来启动

(your_name) D:\vir\your_name>cd your_django_item#进入django文件夹
(your_name) D:\vir\your_name\your_django_item>python manage.py runserver

6.URL conf (URL configuration)的桥梁作用

url(regex, view)
# **regex** -- 定义的 URL 规则
# **view** -- 对应的 view function

接下来,我们来讲一下Templates:

  1. 创建一个名为 templates的文件夹,和app项目在同一级就行
 mkdir templates

2.设定Django项目下的setting文件,为了找到刚新建的templates文件夹

# mysite/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

原先的‘DIRS’为【】,改为上面所示。

3.在templates文件夹下创建hello_world.html文件:

<!-- hello_world.html -->

<!DOCTYPE html>
<html>
    <head>
        <title>I come from template!!</title>
        <style>
            body {
               background-color: lightyellow;
            }
            em {
                color: LightSeaGreen;
            }
        </style>
    </head>
    <body>
        <h1>Hello World!</h1>
        <em>{{ current_time }}</em>
    </body>
</html>

4.将 view function hello_world修改如下:

# views.py

from datetime import datetime
from django.shortcuts import render


def hello_world(request):
    return render(request, 'hello_world.html', {
        'current_time': str(datetime.now()),
    })

展示目前的时间: 为了显示动态內容,我们 import datetime 时间模块,并用datetime.now()取得现在的时间。

render: 我们改成用 render这个 function 产生要回传的 HttpResponse 物件。

这次传入的参数有:

  • request -- HttpRequest物件
  • template_name -- 要使用的 template
  • dictionary -- 包含要新增至 template 的变数

5.ok

Hello World!

2016-08-10 10:39:20.179413

相关文章

网友评论

      本文标题:Python实战计划week4_0_3项目

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