Django站点管理为admin应用,使用的是的django.contrib.auth.models中的User模型。
我要实现的是使用自定义的模型,因为Django的auth很好用,也没必要自己写,所以验证使用的是Django提供的auth框架。
说明:
应用名称为myadmin,确保settings.py中auth的中间件都已使用(默认是打开的)
步骤:
1.models.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 | from django.db import models
import hashlib #为了给密码加密
class User(models.Model):
account = models.CharField(max_length = 30 ,unique = True )
password = models.CharField(max_length = 30 )
def __unicode__( self ):
return self .account
def hashed_password( self ,password = None ):
if not password:
return self .password
else :
#生成password的md5码,hexdigest()即为取得哈希码的16进制字符串
return hashlib.md5(password).hexdigest()
#以下函数必须定义
def is_authenticated( self ):
return True
def check_password( self ,password):
if self .hashed_password(password) = = self .password:
return True
else :
return False
|
2.新建一个auth.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from myadmin.models import User
class UserAuth( object ):
def authenticate( self ,account = None ,password = None ):
try :
user = User.objects.get(account = account)
except User.DoesNotExist:
pass
else :
if user.check_password(password):
return user
return None
#request.user获得的User对象就是get_user()这个函数返回的对象,当对象不存在返回AnonymousUser
def get_user( self ,user_id):
try :
#其中pk即指primary key,当初我擅自换掉浪费一天来查找原因- -
return User.objects.get(pk = user_id)
except User.DoesNotExist:
return None
|
3.settings.py中添加自定义的验证后台
1 2 3 4 5 6 7 | #其余省略
AUTHENTICATION_BACKENDS = (
'myadmin.auth.UserAuth' ,
)
#若不设置,则默认为'django.contrib.auth.backends.ModelBackend'
#验证时从上往下选取
|
4.在视图中使用自定义后台验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
def login_view(request):
#首先返回一个表单response,这里就不写出来了
#具体根据自己的表单来写
if request.mothed = = 'POST' :
account = request.POST[ 'account' ]
password = request.POST[ 'password' ]
user = authenticate(account = account,password = password)
if user is not None :
login(request,user)
#重定向就随意了,自己看着办
return HttpResponseRedirect( '/' )
def logout_view(request):
#匿名调用也不会报异常
logout(request)
return HttpResponseRedirect( '/' )
|
大概就这些,还有一些细节东西,写起来挺累的,有时间再补充
|