Window上python开发--4.Django的用户登录模块User


在搭建网站和web的应用程序时,用户的登录和管理是几乎是每个网站都必备的。今天主要从一个实例了解以下django本身自带的user模块。本文并不对user进行扩展。

主要使用原生的模块。

1.User模块基础:

在使用user 之前先import到自己的iew中。相当与我们自己写好的models。只不过这个是系统提供的models。

from django.contrib.auth.models import User # 导入user模块


1.1User对象属性

User 对象属性:username, password(必填项)password用哈希算法保存到数据库
email,last_login,date_joined(字面意思就知道了)
is_staff ; 用户是否拥有网站的管理权限.
is_active : 是否允许用户登录, 设置为``False``,可以不用删除用户来禁止 用户登录


1.2User 对象方法

is_authenticated(): 如果是真正的 User 对象,返回值恒为 True 。 用于检查用户是否已经通过了认证。通过认证并不意味着 用户拥有任何权限,甚至也不检查该用户是否处于激活状 态,这只是表明用户成功的通过了认证。
这个方法很重要, 在后台用request.user.is_authenticated()判断用户是否已经登录,如果true则可以向前台展示request.user.name

:set_password(passwd)

这个方法是用来更改密码的,先用user=User.objects.get(username='')
user.set_password(passeord='')
user.save

check_password(passwd)

用户需要修改密码的时候 首先要让他输入原来的密码 ,如果给定的字符串通过了密码检查,返回 True

email_user(subj, msg)

给用户发送电子邮件,用 DEFAULT_FROM_EMAIL 的设 置作为发件人。也可以用第3个参数 from_email 来 覆盖设置。



1.3;创建User用户

使用 create_user 辅助函数创建用户:
from django.contrib.auth.models import User
user = User.objects.create_user(username='',password='',email='')
user.save 注意这里不是save()!



1.4. 登录和认证

Django 在 django.contrib.auth 中提供了两个函数来处理这些事情—— authenticate() 和 login()

authenticate(): 认证给出的用户名和密码,使用 authenticate() 函数。它接受两个参数,用户名 username 和 密码 password ,并在密码对用给出的用户名是合法的情况下返回一个 User 对象。当给出的密码不合法的时候 authenticate() 函数返回 None
login() :该函数接受一个 HttpRequest 对象和一个 User 对象作为参数并使用Django的会话( session )框架把用户的ID保存在该会话中
from django.contrib import auth
user = auth.authenticate(username=username, password=password)
if user:
auth.login(request, user)

1.5.注销和重定向

注销 logout()该函数接受一个 HttpRequest 对象作为参数,没有返回值
auth.logout(request)

重定向:HttpResponseRedirect()该函数主要实现,url的重定向。

在我们登录和注销后,重定向到指定url。该函数可以采用url的硬编码。

return HttpResponseRedirect('/sbook/sb_show')

2.实现用户注册和登录

通过上面的基础知识,我们已经了解如何创建和更新一个user啦。接下来用一个实例来做一下用户的注册和登录。

案子mvc的模型,系统已经提供了model,所以我们要做的只需要实现iew和template就行了。在view.py 中实现对注册和登录的控制。

先看以下view中的代码

def alogin(request):
    errors= []
    account=None
    password=None
    if request.method == 'POST' :
        if not request.POST.get('account'):
            errors.append('Please Enter account')
        else:
            account = request.POST.get('account')
        if not request.POST.get('password'):
            errors.append('Please Enter password')
        else:
            password= request.POST.get('password')
        if account is not None and password is not None :
             user = authenticate(username=account,password=password)
             if user is not None:
                 if user.is_active:
                     login(request,user)
                     return HttpResponseRedirect('/index')
                 else:
                     errors.append('disabled account')
             else :
                  errors.append('invaild user')
    return render_to_response('account/login.html', {'errors': errors})
def register(request):
    errors= []
    account=None
    password=None
    password2=None
    email=None
    CompareFlag=False

    if request.method == 'POST':
        if not request.POST.get('account'):
            errors.append('Please Enter account')
        else:
            account = request.POST.get('account')
        if not request.POST.get('password'):
            errors.append('Please Enter password')
        else:
            password= request.POST.get('password')
        if not request.POST.get('password2'):
            errors.append('Please Enter password2')
        else:
            password2= request.POST.get('password2')
        if not request.POST.get('email'):
            errors.append('Please Enter email')
        else:
            email= request.POST.get('email')

        if password is not None and password2 is not None:
            if password == password2:
                CompareFlag = True
            else :
                errors.append('password2 is diff password ')


        if account is not None and password is not None and password2 is not None and email is not None and CompareFlag :
            user=User.objects.create_user(account,email,password)
            user.is_active=True
            user.save
            return HttpResponseRedirect('/account/login')


    return render_to_response('account/register.html', {'errors': errors})

def alogout(request):
    logout(request)
    return HttpResponseRedirect('/index')

从以上的代码中,我们是在template里创建的form。

在templates下创建account目录。在下面创建login.html




    Welcome login 


    

Account Login

{% if errors %}
  • {% for error in errors %}

    Please correct the error: {{error}} below.

    {% endfor %}
  • {% endif %}
    同样的方式创建register.html

    
    
        Welcome Register New Account
    
    
    
     {% if errors %}
            
  • {% for error in errors %}

    Please correct the error: {{error}} below.

    {% endfor %}
  • {% endif %}
    接下来view和template创建好了,只有床urls的映射关系啦。

     url(r'^account/login/$', alogin),
        url(r'^account/register/$', register),
        url(r'^account/logout/$', alogout),
    ok到此为止,用户的注册和登录就可以在在浏览器上看到效果啦。






    评论关闭