1. 程式人生 > >Django入門:登入、註冊、退出

Django入門:登入、註冊、退出

廢話不多說,直接上操作

  • 一、建立專案
django-admin startproject form_test
  • 二、建立應用
cd form_test
sudo ./manage.py startapp form_app
  • 三、配置應用
vim setting.py
#在INSTALLED_APPS新增剛建立的應用('form_app')
  • 四、建立url(form_test/urls.py)
#form_test/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import
admin urlpatterns = patterns('', # Examples: # url(r'^$', 'form_test.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^$', 'form_app.views.login',name='login'), url(r'^login/$', 'form_app.views.login',name='login'
), url(r'^regist/$', 'form_app.views.regist',name='regist'), url(r'^index/$', 'form_app.views.index',name='index'), url(r'^logout/$', 'form_app.views.logout',name='logout'), url(r'^share/$', 'form_app.views.share',name='share'), )
  • 五、建立資料庫物件(form_app/models.py)
from django.db import models

# Create your models here.
class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __unicode__(self): return self.username
  • 六、編寫檢視(/form_app/views.py)
#coding:utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from models import User
# Create your views here.

#表單
class UserForm(forms.Form):
    username = forms.CharField(label='使用者名稱',max_length=100)
    password = forms.CharField(label='密__碼',widget=forms.PasswordInput())

def regist(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            #獲取表單資料
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #新增到資料庫
            #User.objects.get_or_create(username = username,password = password)
            registAdd = User.objects.get_or_create(username = username,password = password)[1]
            if registAdd == False:
                #return HttpResponseRedirect('/share/')
                return render_to_response('share.html',{'registAdd':registAdd,'username':username})
            else:
                return render_to_response('share.html',{'registAdd':registAdd})

    else:
        uf = UserForm()
    return render_to_response('regist.html',{'uf':uf},context_instance=RequestContext(req))

def login(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            #對比提交的資料與資料庫中的資料
            user = User.objects.filter(username__exact = username,password__exact = password)
            if user:
                #比較成功,跳轉index
                response = HttpResponseRedirect('/index/')
                #將username寫入瀏覽器cookie,失效時間為3600
                response.set_cookie('username',username,3600)
                return response
            else:
                return HttpResponseRedirect('/login/')
    else:
        uf = UserForm()
    return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
#登入成功
def index(req):
    username = req.COOKIES.get('username','')
    return render_to_response('index.html',{'username':username})
#退出登入

def logout(req):
    response = HttpResponse('logout!!!')
    #清除cookie裡儲存的username
    response.delete_cookie('username')
    return response

def share(req):
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']

            return render_to_response('share.html',{'username':username})
    else:
        uf = UserForm()
    return render_to_response('share.html',{'uf':uf})
  • 七、建立templates(form_app/templates)
cd templates
sudo touch share.html regist.html login.html logout.html index.html
# vim share.html

{{registAdd}} 
<br>
==================
<br>
{% if  username %}
註冊失敗{{username}}已存在
<a href="http://127.0.0.1:8000/regist">註冊</a>
{% else %}
註冊成功!
<a href="http://127.0.0.1:8000/login">登入</a>
{% endif %}
# vim regist.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Regist</title>
</head>
<body>
<h1>註冊頁面</h1>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{uf.as_p}} 
    <input type="submit" value="ok"></input>
</form>
<a href="http://127.0.0.1:8000/login">登入</a>
</body>
</html>
# vim login.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Login</title>
</head>
<body>
<h1>登入頁面</h1>
<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{uf.as_p}} 
    <input type="submit" value="ok"></input>
</form>
<a href="http://127.0.0.1:8000/regist">註冊</a>
</body>
</html>
# vim index.html

<!DOCTYPE html>
<html>
<head>
    <title>index</title>
</head>
<body>
<h1>Welcome {{ username }}!</h1>
<br>
<a href="http://127.0.0.1:8000/logout">退出</a>
</body>
</html>