Python · 2011-07-26

django简单的入门例子

建立项目:django-admin.py startproject test1

建立目录:django-admin.py startapp views

django-admin.py startapp db

django-admin.py startapp templates

hello.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python
#-*-coding:utf-8-*-
from django.http import HttpResponse
from django.template import Context,Template
from django.template.loader import get_template
from django.shortcuts import render_to_response
 
import datetime
def current_time(request):
    now=datetime.datetime.now()
    html="It is now %s ." %now
    return HttpResponse(html)
 
def hours_ahead(request,offset):
    offset=int(offset)
    dt=datetime.datetime.now()+datetime.timedelta(hours=offset)
    html="In %s hour(s) ,it will be %s." %(offset,dt);
    return HttpResponse(html)
 
def hours_after(request,offset):
    offset=int(offset)
    dt=datetime.datetime.now()-datetime.timedelta(hours=offset)
    html="%s hour(s) ago,it will be %s." %(offset,dt);
    return HttpResponse(html)
 
# plus_or_minus和offset参数由urls.py中设置,这里的设置是
#(r'^now/(plus|minus)(\d{1,2})hours/$', hello.hours_offset),
#与位置顺序有关
def hours_offset(request,plus_or_minus,offset):
    offset=int(offset)
    if plus_or_minus=='plus':
        dt=datetime.datetime.now()+datetime.timedelta(hours=offset)
        html="In %s hour(s) ,it will be %s." %(offset,dt);
    else:
         dt=datetime.datetime.now()-datetime.timedelta(hours=offset)
         html="%s hour(s) ago,it will be %s." %(offset,dt)
    return HttpResponse(html)
 
#使用模板
def t_current_time(request):
    now=datetime.datetime.now()
    html="It is now {{current_time}}."
    t=Template(html)
    c=Context({'current_time':now})
    ret=t.render(c)
    return HttpResponse(ret)
 
#使用模板,需要在setting.py文件里配置TEMPLATE_DIRS , 在这里的地址是'f:/django/test1/templates',
def tl_current_time(request):
    now=datetime.datetime.now()
    t=get_template('current_time.html')
    c=Context({'current_time':now})
    ret=t.render(c)
    return HttpResponse(ret)
 
#使用render_to_response()方法渲染模板
def render_current_time(request):
    now=datetime.datetime.now()
    return render_to_response('current_time.html',{'current_time':now})
 
def renderl_current_time(request):
    current_time=datetime.datetime.now()
    #locals()返回一个包含当前作用域里面的所有变量和他们的值的字典
    #在这里就相当于{'current_time':current_time}
    return render_to_response('current_time.html',locals())
 
#前台循环
def musician_list(request):
    MUSICIANS = [
        {'name': 'Django Reinhardt', 'genre': 'jazz'},
        {'name': 'Jimi Hendrix',     'genre': 'rock'},
        {'name': 'Louis Armstrong',  'genre': 'jazz'},
        {'name': 'Pete Townsend',    'genre': 'rock'},
        {'name': 'Yanni',            'genre': 'new age'},
        {'name': 'Ella Fitzgerald',  'genre': 'jazz'},
        {'name': 'Wesley Willis',    'genre': 'casio'},
        {'name': 'John Lennon',      'genre': 'rock'},
        {'name': 'Bono',             'genre': 'rock'},
        {'name': 'Garth Brooks',     'genre': 'country'},
        {'name': 'Duke Ellington',   'genre': 'jazz'},
        {'name': 'William Shatner',  'genre': 'spoken word'},
        {'name': 'Madonna',          'genre': 'pop'},
    ]
    return render_to_response('musician_list.html',{'musicians':MUSICIANS})

urls.py

这里开通了django的后台管理的功能,1.0版本与0.96版本不太一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
#from test1.views.hello import current_time
from test1.views import hello
from test1.views import test_form
from test1.views import login
 
urlpatterns = patterns('',
    # Example:
    # (r'^test1/', include('test1.foo.urls')),
    #(r'^index/', include('test1.test.index')),
    (r'^now/$', hello.current_time),
    #(r'^now/plus(\d{1,2})hours/$', hello.hours_ahead),
    #(r'^now/minus(\d{1,2})hours/$', hello.hours_after),
    (r'^now/(plus|minus)(\d{1,2})hours/$', hello.hours_offset),
    (r'^tnow/$', hello.t_current_time),
    (r'^tlnow/$', hello.tl_current_time),
    (r'^rnow/$', hello.render_current_time),
    (r'^rlnow/$', hello.renderl_current_time),
    (r'^list/$', hello.musician_list),
    (r'^forms/$', test_form.search),
    (r'^login/$', login.login),
 
    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
 
    # Uncomment the next line to enable the admin:
    (r'^admin/(.*)', admin.site.root),
)

数据库的简单操作:

这里与0.96似乎有很大的差别,

0.96的版本是class Admin: pass 这样加入admin的管理后台去

而1.0之后的版本则是通过admin.site.register(User) 这个语句是把User表加入到admin的管理后台去

另外也有变化,则需要参考文档,还没有使用那部分的功能

这是models.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from django.db import models
from django.contrib import admin
 
# Create your models here.
 
class User(models.Model):
    id = models.IntegerField(primary_key=True)
    username = models.CharField(max_length=150, blank=True)
    password = models.CharField(max_length=150, blank=True)
 
class TUser(models.Model):
    username = models.CharField(max_length=150, blank=True)
    password = models.CharField(max_length=150, blank=True)
 
admin.site.register(User)
admin.site.register(TUser)

应用:test_form.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python
#-*-coding:utf-8-*-
from django.db.models import query
from django.db.models import Q
from django.shortcuts import render_to_response
from test1.db.models import TUser
 
def search(request):
    queryStr=request.GET.get('q','')
    #print request.GET.get('q','')
    #查询所有的对象
    #all=TUser.objects.all()
    #查询指定的对象
    #all=TUser.objects.filter(username='test')
    #查询大于test2的对象
    #all=TUser.objects.filter(username__gte='test2')
    #startswith 相当于WHERE username LIKE 'test%'
    #all=TUser.objects.filter(username__startswith='test').filter(password='test')
    #Q对象 |表示or &表示and
    qset=(Q(username='test6')&Q(password='test6'))
    all=TUser.objects.filter(qset)
 
    #if queryStr=='':
    #    all=TUser.objects.all()
    #else:
    #    all=TUser.objects.filter(username=queryStr)
 
    #print all
    #results = User.objects
    #if request.method=='POST':
    #    print 1
    #else:
    #    print 2
    return render_to_response('formtest.html',{'all':all,'queryStr':queryStr})

templates:formtest.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en"> <head>
<title>Search{% if query %} Results{% endif %}</title>
</head> <body>
<h1>Search</h1>
<form action="." method="GET">
<label for="q">Search: </label>
<input type="text" name="q" value="{{ queryStr|escape }}">
<input type="submit" value="Search">
</form>
<ul>
    {% for a in all %}
<li>{{a.username}}-------------{{a.password}}</li>  
{% endfor %}
 
</ul>
 
</body>
</html>

用户登录例子:login.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
#-*-coding:utf-8-*-
from django.http import HttpResponse
from test1.db.models import TUser
from django.shortcuts import render_to_response
 
def login(request):
    username=request.GET.get('username','')
    password=request.GET.get('password','')
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("SELECT count(*) FROM db_tuser WHERE username = %s group by id", [username])
    row = cursor.fetchone()
    print row
 
    return testsss(username,password)
   #if request.session.get('username')==username:
   #     return HttpResponse(username+' is login')
   # flag=checkLogin(username,password)
   # if flag==1:
   #     request.session['username']=username
   #     return HttpResponse('login success!')
   # else:
   #     return HttpResponse('login error')
    #return render_to_response('login.html',{'username':username,'info':''})
 
def testsss(username,password):
    flag=checkLogin(username,password)
    if flag==1:
        return HttpResponse('login success!')
    else:
        return HttpResponse('login error')
 
def checkLogin(username,password):
    try:
        m=TUser.objects.get(username=username)
        if password==m.password:
            #print 'login success'
            return 1
        else:
            #print 'password is error'
            return 2
    except:
        #print 'username is error'
        return 3

页面:login.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{% extends "base.html" %}
{% block title %}login{% endblock %}  
 
{% block content %}
<form action="." method="GET">
<label for="q">login: </label>
<div>用户名:<input type="text" name="username" value="{{ username|escape }}" /></div>
<div>密码:<input type="password" name="password" value="" /></div>
<div><input type="submit" value="login"></div>
</form>
 
<p>
    {% for a in info   %}
    <div>username:{{a.username|escape}}------------password:{{a.password|escape}}</div>    
    {% endfor %}
</p>
 
{% endblock %}

base.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!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>

django 框架, 模板在templates中 ,样式和图片在site_media,

templates/index.html

文件内容:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
<link href="/site_media/admin/css/manager.css" rel="stylesheet" type="text/css" media="screen" />
 
<link href="/site_media/admin/css/manager.css" rel="stylesheet" type="text/css" media="screen" />

没有没什么方法可以在templates中的文件只用写 <link href=”css/manager.css” rel=”stylesheet” type=”text/css” media=”screen” />

这样美工做完页面后只用拿过来加入数据就可以了,而不用在改样式图片的路径。

在url.py中

1
2
3
4
import os
site_media = os.path.join(
os.path.dirname(__file__),'site_media/admin/css/'
)

然后

1
2
3
urlpatterns = patterns('',
(r'^css/(?P<path>.*)$','django.views.static.serve',
{ 'document_root': site_media }),

就可以了。