臨近年底,各種忙,好久沒更新博客了,2017春節假期在即,距下班還有2小時,難得閒下來,來擼一手django簡單的web註冊,登錄,註銷。
環 境:centos 6.4 64bit
python :python 2.7.8
django :1.9.6
author:soul
date :2017-01-24
1、創建一個項目project 名爲sheying
#django-admin startproject sheying
2、創建一個項目應用app 名爲danfan
#python manage.py startapp danfan
3、創建一個模板目錄,存放html展示頁面
在danfan目錄下mkdir templeates
4、設置項目sheying 的settings參數
添加app應用以及模板路徑,數據庫鏈接
TEMPLATE_DIRS = (
'/usr/local/python27/sheying/danfan/templeates',
)
INSTALLED_APPS = (
#添加app
'danfan',
)
MIDDLEWARE_CLASSES中添加中文支持,註釋安全檢測
'django.middleware.locale.LocaleMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', //這裏用的是mysql
'NAME': 'sheying', //數據庫名
'USER': 'soul', //用戶名
'PASSWORD': 'password',//密碼
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
5、在danfan目錄下定義數據模型models(User,Info)
User: 用於存在用戶註冊的用戶數據
Info:用於存在圖片的信息詳細。
models.py
# -*-coding:utf-8 -*-
from django.db import models
class User(models.Model):
username = models.CharField('用戶名',max_length=32)
password = models.CharField('密碼',max_length=32)
email = models.EmailField('郵箱')
def __unicode__(self):
return self.username
class Info(models.Model):
BRAND_CHOICES = (
('Canon', 'Canon'),
('Nikon', 'Nikon'),
('Sony', 'Sony'),)
TYPE_CHOICES = (
('風景', '風景'),
('人像', '人像'),
('寫真', '寫真'),)
title = models.CharField('標題',max_length=64)
type = models.CharField('類型',choices=TYPE_CHOICES, max_length=16, default = '風景')
author = models.CharField('攝影師',max_length=32)
place = models.CharField('拍攝場所',max_length=64)
brand = models.CharField('品牌',choices=BRAND_CHOICES, max_length=16,default='Nikon')
model = models.CharField('型號',max_length=16)
scene = models.CharField('鏡頭',max_length=64)
description = models.TextField('描述',blank=True, null=True)
def __unicode__(self):
return self.title
定義表單 forms.py (用於註冊和登錄信息框輸入)
# -*-coding:utf-8 -*-
from django import forms
class UserForm(forms.Form):
username = forms.CharField(label='賬號:',max_length=16, error_messages={'required': '請填寫您的稱呼','max_length': '稱呼太長'})
password = forms.CharField(label='密碼:',widget=forms.PasswordInput(),error_messages={'required': '請填寫密碼'})
email = forms.EmailField(label='郵箱:',error_messages={ 'required': '請輸入你的郵箱','invalid': '郵箱格式不正確'})
class LoginForm(forms.Form):
username = forms.CharField(label='賬號:',max_length=16, error_messages={'required': '請輸入用戶名','max_length':'用戶名太長'})
password = forms.CharField(label='密碼:',widget=forms.PasswordInput(),error_messages={'required': '請輸入密碼'})
6、同步數據,生成數據表和表單(1.7以上版本)
#python manage.py syncdb
# python manage.py makemigrations
# python manage.py migrate
(創建管理員賬號過程略......)
7、創建視圖(danfan目錄下的views.py)
#coding=utf-8
from django.shortcuts import render
from forms import UserForm
from forms import LoginForm
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from .models import User,Info
#註冊用戶
def register(request):
if request.method == "POST":
uf = UserForm(request.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
email = uf.cleaned_data['email']
User.objects.create(username= username,password=password,email=email)
return render_to_response('success.html',{'username':username})
else:
uf = UserForm()
return render_to_response('register.html',{'uf': uf})
#登錄賬號
def login(request):
if request.method == "POST":
uf = LoginForm(request.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:
response = HttpResponseRedirect('/danfan/add')
response.set_cookie('username',username,3600)
return response
else:
return HttpResponseRedirect('/danfan/login')
else:
uf = LoginForm()
return render_to_response('login.html',{'uf': uf})
#添加圖片分享
def add(request):
if request.method == 'GET':
return render(request,'add.html')
elif request.method == 'POST':
title = request.POST['title']
type = request.POST['type']
author = request.POST.get('author', '')
place = request.POST.get('place', '')
brand = request.POST['brand']
model = request.POST.get('model', '')
scene = request.POST.get('scene', '')
description = request.POST.get('description', '')
info = Info.objects.filter(title=title)
if info:
return HttpResponse('Title %s have been exist' % title)
info = Info(title=title, type=type, author=author, place=place, brand=brand, model=model, scene=scene, description=description)
info.save()
#return HttpResponse('Add title %s success' % title)
return HttpResponseRedirect('/danfan/list')
else:
return HttpResponse('Not support method %s' % request.method)
#list列表
def list(request):
#article = Article.objects.get(id=id)
#self_infos = Info.objects.filter(Info=id).order_by("-id").all()
self_infos = Info.objects.order_by("-id").all()
return render_to_response('index.html', {'self_infos': self_infos})
#註銷
def logout(request):
#response = HttpResponse('logout')
#response.delete_cookie('username')
#return response
return HttpResponseRedirect('/danfan/login')
8、配置url路徑
項目sheying 下urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^danfan/', include('danfan.urls')), //將danfan目錄路徑include進來
)
應用danfan下的urls.py
from django.conf.urls import patterns, url
from danfan import views
urlpatterns = patterns('',
url(r'^$',views.register, name='register'),
url(r'^register/$',views.register,name = 'register'),
url(r'^login/$',views.login,name = 'login'),
url(r'^add/$',views.add,name = 'add'),
url(r'^list/$',views.list,name='list'),
url(r'^logout/$',views.logout,name = 'logout'),
register:註冊頁面url
login: 登錄頁面url
add: 添加頁面url
list: 列表頁面url
logout: 註銷頁面url
9、創建html模板(存放在templeates目錄下)
register.html 註冊頁面
<!DOCTYPE html>
<html>
<head>
<title>小蜜蜂</title>
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
</head>
<style type="text/css">
body{background:#efd;padding:100 5em;margin:10;
background-image="/usr/local/python27/cenxi/hunlianwang/templeates/images/index.jpg";
background-size:cover;
}
h1{padding:2em 0.5em;background:#687}
h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
p{margin:1em 0}
</style>
<body>
<button type="button" class="btn btn-default">首頁</button>
<button type="button" class="btn btn-primary">相約小蜜蜂</button>
<button type="button" class="btn btn-success">美圖分享</button>
<button type="button" class="btn btn-info">攝影之旅</button>
<button type="button" class="btn btn-warning">拍攝技巧</button>
<button type="button" class="btn btn-danger">關於我們</button>
<br>
<div>
<form method = 'post' enctype="multipart/form-data">
{% csrf_token %}
`uf`.`as_p`
<input class="btn btn-warning" type="submit" value = "註冊用戶" />
<a href="/danfan/login/" color='#bf8'> 登錄 </a>
</form>
</div>
</body>
</html>
login.html 登錄頁面
(這裏只簡寫body部分,head title等直接繼承beas.html即可)
<html>
<body>
<div>
<form method = 'post' enctype="multipart/form-data">
{% csrf_token %}
`uf`.`as_p`
<input class= "btn btn-success" type="submit" value = "登陸" >
</form>
</div>
</body>
</html>
添加圖片信息頁面add.html
(這裏只簡寫body部分,head title等直接繼承beas.html即可)
<html>
<body>
<div>
<H3>分享我的照片</H3>
<br />
<form action="" method="post">
{% csrf_token %}
<div>
<label for="title">標題:</label>
<input name="title" id="title">
</div>
<br />
<div>
<label for="type">類型:</label>
<select name="type" id="type">
<option value="風景">風景</option>
<option value="人像">人像</option>
<option value="寫真">寫真</option>
</select>
</div>
<br />
<div>
<label for="author">攝影:</label>
<input name="author" id="author">
</div>
<br />
<div>
<label for="place">場地:</label>
<input name="place" id="place">
</div>
<br />
<div>
<label for="brand">品牌:</label>
<select name="brand" id="brand">
<option value="Canon">Canon</option>
<option value="Nikon">Nikon</option>
<option value="Sony">Sony</option>
</select>
</div>
<br />
<div>
<label for="model">型號:</label>
<input name="model" id="model">
</div>
<br />
<div>
<label for="scene">鏡頭:</label>
<input name="scene" id="scene">
</div>
<br>
<div>
<label for="description">描述:</label>
<textarea name="description" cols="22" rows="5"></textarea>
</div>
<br>
<div>
<input class="btn btn-success" type="submit" value="保存">
</div>
</form>
</body>
</html>
列表頁面 list.html
(這裏只簡寫body部分,head title等直接繼承beas.html即可)
<html>
<body>
<div>
<H3>我的圖片分享</H3>
<br />
<table color="CCCC33" width="800" border="0" cellpadding="5" >
<tr>
<td><h4>標題 </h4></td>
<td><h4>類型 </h4></td>
<td><h4>攝影 </h4></td>
<td><h4>場地 </h4></td>
<td><h4>品牌 </h4></td>
<td><h4>型號 </h4></td>
<td><h4>鏡頭 </h4></td>
<td><h4>描述 </h4></td>
<td colspan="2"><h4>操作 </h4></td>
</tr>
{% for info in self_infos %}
<tr>
<td><h5>`info`.`title`</h5></td>
<td><h5>`info`.`type`</h5></td>
<td><h5>`info`.`author`</h5></td>
<td><h5>`info`.`place`</h5></td>
<td><h5>`info`.`brand`</h5></td>
<td><h5>`info`.`model`</h5></td>
<td><h5>`info`.`scene`</h5></td>
<td><h5>`info`.`description`</h5></td>
<td><h5><a href="` info`.`id `/">詳情</a></h5></td>
<td><h5><a href="` info`.`id `/delete/">刪除</a></h5></td>
</tr>
{% endfor%}
</table>
<br />
<br />
<a href="/danfan/logout/" color='#bf8'>退出 </a>
</body>
</html>
訪問測試
A:訪問http://192.168.101.52:6666/danfan
不填寫用戶信息會有一個判斷
註冊一個小茗同學 的賬戶
註冊成功,添加分享的圖片信息
保存信息內容
先寫到這裏了,還有圖片上傳、詳情、評論、刪除等功能需要優化。
春節放假咯,回去繼續啃書.......在技術控的路上漸行漸遠.大家新年快樂!