django用户认证

 

 

用户登录:

def logon(request):
    errors_list = []
    if request.method == 'POST':
        u = request.POST['uname']
        p = request.POST['upass']
        #验证用户
        user = authenticate(username=u, password=p)
        if user is not None:
            auth_login(request, user)
            #登录成功后重定向到主页
            return HttpResponseRedirect("/sinfors/")
        else:
            try:
                #检查用户密码是否正确
                if not auth_User.objects.get(username = u).check_password(p):
                    errors_list.append(u + ' password is not correct') 
            #检查用户是否存在(auth_User.objects.get(username = u))
            except auth_User.DoesNotExist:
                errors_list.append(u + ' does not exist') 

    return render(request, 'sinfors/login.html', {'errors_list':errors_list})

 

页面添加认证:

#对页面增加验证
@login_required(login_url="/sinfors/logon/") 
def index(request):
    servers = infor.objects.all()
    #验证如果用户登录成功,则取相应的用户名显示在主页
    if not request.user.is_anonymous():
        user_loggedin = request.user
    else:
        user_loggedin = 'Guest'
    context = {'servers':servers,'user_loggedin':user_loggedin}
    return render(request,'sinfors/index.html',context)

 

新增用户,修改/验证密码:

#新建用户
user = User.objects.create_userusername='',password='',email='')
user.save #不使用user.save()

#重置密码
user.set_password(passeord='')
user.save 

#检查用户输入的密码是否正确
user.check_password('password')

 

扩展用户字段:

model:

class UserProfile(models.Model):  
    user=models.OneToOneField(User,unique=True)
    phone=models.CharField(max_length=20)
    addr=models.CharField(max_length=500)

    def ztest(self):
        if len(self.phone) < 8:
            return 'The phone num is not correct'
        else:
            return 'The phone num is  correct'

    def phone_len(self):
        return len(self.phone)
    p_len = property(phone_len)  #custom a property

 

print request.user.userprofile.phone
          print request.user.userprofile.user
          print request.user.UserProfile
          print dir(UserProfile)
          UserProfile.C_userp('test01','03129999999','HB'):
            
          u = auth_User.objects.get(username='test')
          a=UserProfile.objects.get(user=u)
          print a.ztest()
          print a.p_len
            

          uu=request.user
          u = auth_User.objects.get(username=uu)
          a=UserProfile.objects.get(user=u)
          print dir(UserProfile.objects)
          print a
          UserProfile.C_userp(uu,'12345','AH')

 

posted on 2016-03-08 15:29  momingliu11  阅读(520)  评论(0编辑  收藏  举报