Django 1.4 Python 2.7菜鸟入门

这次我用的Django是1.4的,python是2.7的,本篇文章的主要目的是为那些刚刚学习django的同学提供一个好的开始。建议参考djangobook。

我们的主要任务是这样的:

在地址栏输入localhost:8000/currenttime/,页面上在正中央显示当前的系统时间,在url后面加上一个数字,那么会在页面下显示该值个小时之后系统的时间。

关于Django和python的安装我在这里便不再多讲,django可以使用easy_install工具来安装。注意这里1.4的django和以往版本的django在生成目录上结构略有不同,它把该工程的配置文件以及urlconfig和wsgi放在一个文件夹中,相当于一个应用程序一样,我想它这样做的目的是想使得工程目录的结构更加优雅吧。

好了开始做吧:

1,使用django-admin.py startproject myTime新建一个工程

2,在这个任务中我们不需要使用数据库,但是我们要明白工程开始的时候各个文件的作用是什么,如下:


__init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。
manage.py :一种命令行工具,可让你以多种方式与该 Django 项目进行交互。
settings.py :该 Django 项目的设置或配置。
urls.py :该 Django 项目的 URL 声明,即 Django 所支撑站点的内容列表


这些都是后台的东西,关于前台,我们还需要一个view.py的文件,来使得特定的url触发不同的界面显示。在myTime下(里面的)新建一个view.py。

3,我们在view中新建的是视图函数,这其中的代码如下所示:

from django.http import HttpResponse
from django.template.loader import get_template
from django.template import *
from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
    current_time = datetime.datetime.now()
    #t = get_template('first.html')
    #c = Context({"current_time":now})
    #html = t.render(c)
    #return HttpResponse(html)
    return render_to_response('first.html',locals())
def time_ahead(request,off):
    current_time = datetime.datetime.now()
    off = int(off)
    da = datetime.datetime.now() + datetime.timedelta(hours=off)

    return render_to_response("child.html",locals())

这是两个视图函数,下面我们把这两个视图函数和url关联起来,其中的html文件是我们的界面模板,有关模板的介绍请参考djangobook,内容太多一时半会也说不清楚,其实就是在html中加入了一些代码,这些代码可以是变量和函数标签,或者是过滤器。关于模板的建立我们接下来要讲,但是我们需要现在myTime(外面的)新建一个templates文件夹,并且在里面新建first.html和child.html两个文件,并且在setting.py中讲template_dir做修改,在其中加入如下代码:

import os.path

ROOT_PATH = os.path.dirname(_file_)

template_dir设置为

os.path.join(ROOT_PATH, '../templates/').replace('\\','/'),

注意由于这里的目录结构和以往版本的不同,所以这里需要加上..

4,修改url

from django.conf.urls import *
from mysite.view import *

urlpatterns = patterns('',

 url(r"^currenttime/$",current_datetime),
    url(r"^currenttime/(\d{1,2})/",time_ahead),
)

注意这里正则表达式的运用,符号^和$分别表示表达式的开头和末尾。

5,设置模板界面,两个界面的代码分别为:

first.html:

<html>
<head>
<title>
my first template html page!
</title>
</head>
<body>
<center>
the time of now is {{current_time}}
<br />
<br />
{%block footer%}
this is my footer
{%endblock%}
</center>
</body>
</html>

第二个界面为child.html:

{%extends "first.html"%}
{%block footer%}
this is my child footer
<br />
<br />
the real time ahead of {{off}} is {{da}}
{%endblock%}


最后运行一个便可以了,还是建议参考djangobook,里面的内容讲的很详细。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值