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 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="<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 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の管理バックグラウンドに追加することです.
また変更もありますので、ドキュメントを参考にする必要がありますが、その部分の機能はまだ使用されていません.
これはモデルです.py

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

#!/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

<!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 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

{% 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>