安迪_963

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
下面的内容来自官方文档
is_active

布尔值。指示用户的账号是否激活。我们建议把这个标记设置为False 来代替删除账号;这样的话,如果你的应用和User 之间有外键关联,外键就不会失效。

它不是用来控制用户是否能够登录。认证的后端没有要求检查is_active 标记,而且默认的后端不会检查。如果你想在is_activeFalse 时拒绝用户登录,你需要在你自己的视图或自定义的认证后端中作检查。但是,默认的login() 视图使用的AuthenticationForm 却会 作这个检查,正如在Django 的Admin 站点中所做的权限检查方法如has_perm() 和认证一样。对于未激活的用户,所有这些函数/方法都返回False

 

 

这里要说的就是将is_active设置为False,来阻止刚 注册的用法登陆

            password = password1
            user_profile = UserProfiles()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.is_active = False
            user_profile.password = make_password(password)
            user_profile.save()

 这里是第一种比较笨办法中的一段代码: 简单粗暴,直接实例化一个对象将其is_active设置为False

 

但是Django自带的auth模块中有更简单的办法, create_user

看下面源码:

    def create_user(self, email, password=None, **extra_fields):

        is_staff = extra_fields.pop('is_staff', False)
        return self._create_user(email=email, password=password, 
                                 is_staff=is_staff, is_superuser=False,
                                 **extra_fields)

 很显然, 常见的字段只有email, password, is_staff, is_supersuer etc. 但是还有一个**extra_fields,

关键就在这个extra_fields中,它可以指定其它所有的字段的值.

下面对上面笨办法的一个补充:

            UserProfiles.objects.create_user(username=user_name, password=password1, is_active=False)

 这里的UserProfiles 和上面的UserProfiles都是自定义的继承自User的Model,如果你没有重写User,这里需要先导入User

from django.contrib.auth.models import User
User.objects.create_user(username=user_name, password=password1, is_active=False) # 并改成这样

 同样的道理,其它字段也可以自己指定.

posted on 2018-03-12 20:04  Andy_963  阅读(1430)  评论(0编辑  收藏  举报