1、Django提供了用户认证的模块,在settings.py中使用如下的代码
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ..... INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', )
2、更新数据库:python manage.py syncdb
3、利用jquery ajax验证用户是否存在
//发出ajax请求 $.getJSON("check/username/", {username:$(this).val()}, function(data){ $("#r_tip").html(data.msg); });
#必须导入的模块 from django.http import HttpRequest from django.http import HttpResponse from django.contrib.auth.models import User from django.utils import simplejson #相应jquery ajax请求 def check_username(request): if request.method == 'GET': try: user = User.objects.get(username = request.GET['username']); if user is not None: return HttpResponse(simplejson.dumps({'msg':'用户名已存在'})) except: return HttpResponse(simplejson.dumps({'msg':'用户名可以使用'}))
4、用户的注册
Ajax请求:
$.getJSON("register/", {username:$('#register_name').val(), password:$('#register_psw').val(), email:$('#register_name').val() }, function(data){ if(data.msg == 'ok') { hideDiv('pop-div'); }else{ alert(data.msg); }
django响应:
def register(request): ''' 功能:往数据库中添加一条用户注册信息 ''' if request.method == 'GET': username = request.GET['username'] password = request.GET['password'] email = request.GET['email'] user = User.objects.create_user(username, email, password) if user is not None: user.save() return HttpResponse(simplejson.dumps({'msg':'ok'})) else: return HttpResponse(simplejson.dumps({'msg':'注册失败'}))
5、用户登录
def login_account(request): ''' 功能:用户登陆到个人首页 ''' username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect("/account/"+username+"/") else: pass else:
6、页面认证,当用户没有登录并访问一个url时,将转接到一个登陆页面
@login_required #调用home函数是要调用login_required函数 def home(request,username): return render_to_response('accounts/home.html') #这个login_required检查到用户没有登录,将跳转到一个url,这个url在seetings.py总添加一个LOGIN_URL = '/',表示没有登录就跳转