django拾遗

1, django-admin.py startproject 创建一个mysite的站点

自动生成 settings.py,views.py,urls.py,__init__.py

2, 执行命令python manage.py runserver运行自带的web服务器,即可看到网站主页面了。

3,在urls.py追踪设置网站的子页 

假设 http://127.0.0.1有两类子页面

1类是http://127.0.0.1/time,固定不带参数的显示当前时间

2类是http://127.0.0.1/time/plus/7,后面这个数字7就是变量值,下面urlpatterns是用正则表达式取得变量的值。 

from django.conf.urls.defaults import *

from mysite.views import current_datetime,hours_ahead
urlpatterns = patterns('',                       (r'^time/$',current_datetime),                       (r'^time/plus/(\d{1,2})/$',hours_ahead),)

4,当网页申请发生时,导向对应的网页解析函数,就是patterns字典后面的current_datetime和hours_ahead

这些函数其实是用来动态生成HTML标记 ,放在view.py中

而为了页面和逻辑分离,把页面放到抽象的模板当中,那么view.py中的解析函数只要对模板中的变量赋值就可以了

 from django.shortcuts import render_to_response

import datetime
def current_datetime(request):
    now=datetime.datetime.now()
    return render_to_response('current_datetime.html',{'current_date':now})
 

def hours_ahead(reqest,offset):

    offset=int(offset)
    dt=datetime.datetime.now()+datetime.timedelta(hours=offset)
    return render_to_response('hours_ahead.html',{'hour_offset':offset,'next_time':dt})
5,模板,从4中我们知道模板是抽象出变量的页面,在settings.py中有规定模板所在的文件夹
import os
TEMPLATE_DIRS = (
                  os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

 

上面两个函数,各对应一个模板文件

 current_datetime.html和hours_ahead.html

这两个模板文件基本内容都差不多,就是内容标题不一样而已

因此而抽象出一个基本的模板base.html,避免模板的重复劳作 ,current_datetime.html和hours_ahead.html继承base.html

这样就有三个模板文件了

 ----------base.html--------

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>

</html> 

 --------------current_datetime.html

{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>

{% endblock %} 

 --------------hours_ahead.html

 {% extends "base.html" %}

{% block title %}Future time{% endblock %}
{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}

 

 

 

posted on 2011-08-22 20:12  步走高飞  阅读(232)  评论(0编辑  收藏  举报

导航