基本的配置已经完成了,来看看最重要的views.py
先看看简单的注册登录功能,在django里有一个专门的模块用来验证用户信息 ;所以只需要调用就好了:
#-*-coding:utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.contrib.auth.models import User #django 自带后台管理模块 from django.contrib import auth from models import * #主页 def index(req): username=req.session.get('username', '') content = {'active_menu': 'homepage', 'user': username} return render_to_response('index.html', content)#将数据返回到前台 #注册 def regist(req): if req.session.get('username', ''):#获取session用来判断用户是否登录 return HttpResponseRedirect('/') status="" if req.POST: username = req.POST.get("username","") #从前台获得用户注册信息,判断,存入数据库 if User.objects.filter(username=username): status = "user_exist" else: password=req.POST.get("password","") repassword = req.POST.get("repassword","") if password!=repassword: status = "re_err" else: newuser=User.objects.create_user(username=username,password=password) newuser.save() new_myuser = MyUser(user=newuser,phone=req.POST.get("phone")) new_myuser.save() status = "success" return HttpResponseRedirect("/login/") return render_to_response("regist.html",{"active_menu":"hompage","status":status,"user":""},context_instance=RequestContext(req)) #登录 def login(req): if req.session.get('username', ''): return HttpResponseRedirect('/') status="" if req.POST: username=req.POST.get("username","") password=req.POST.get("password","") user = auth.authenticate(username=username,password=password) if user is not None: auth.login(req,user) req.session["username"]=username #保存登录会话 return HttpResponseRedirect('/') else: status="not_exist_or_passwd_err" return render_to_response("login.html",{"status":status},context_instance=RequestContext(req)) #退出登录 def logout(req): auth.logout(req) return HttpResponseRedirect('/')
注册、登录是对数据库的基本增、查;而django提供了高级API
使用filter()方法来过滤数据,判断用户名是否在数据库中:
User.objects.filter(username=username)
相当于SQL语句:
SELECT username FROM auth_user WHERE username=username;
使用create_user辅助函数创建用户,只用了username和password两个属性;这里User和MyUser是一对一的关系,用户名和密码直接调用,然后加上用户电话号码
User.objects.create_user(username=username,password=password) MyUser(user=newuser,phone=req.POST.get("phone"))
以上只是表示准备向数据库存的数据,完了后要用.save()才能存到数据库里
相当于SQL语句:
INSERT INTO auth_user(username,password) VALUES ("username","password");
auth的authenticate()函数验证用户名和密码,不用再查数据库:
auth.authenticate(username=username,password=password) auth.login(req,user) #auth的login()函数是登录 auth.logout(req) #auth的logout()函数是注销
到此,一个简单的注册登录就完成了。