django简单的入门例子

来源:互联网 发布:外汇智能分析软件 编辑:程序博客网 时间:2024/05/17 22:44

关键字: django简单的入门例子

django入门例子:

都是参考了网上的例子完成的~

建立项目:django-admin.py startproject test1
建立目录:django-admin.py startapp views
         django-admin.py startapp db
         django-admin.py startapp templates

附件为所有代码

hello.py
如下:
#!/usr/bin/env python#-*-coding:utf-8-*-from django.http import HttpResponsefrom django.template import Context,Templatefrom django.template.loader import get_templatefrom django.shortcuts import render_to_responseimport datetimedef 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="<body><html>It is now {{current_time}}</html></body>."     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版本不太一样
from django.conf.urls.defaults import *# Uncomment the next two lines to enable the admin:from django.contrib import adminadmin.autodiscover()#from test1.views.hello import current_timefrom test1.views import hellofrom test1.views import test_formfrom test1.views import loginurlpatterns = 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
from django.db import modelsfrom 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
#!/usr/bin/env python#-*-coding:utf-8-*-from django.db.models import queryfrom django.db.models import Qfrom django.shortcuts import render_to_responsefrom test1.db.models import TUserdef 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
<!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
#!/usr/bin/env python#-*-coding:utf-8-*-from django.http import HttpResponsefrom test1.db.models import TUserfrom django.shortcuts import render_to_responsedef 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
{% 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
<!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> 
原创粉丝点击