django系列1 - User Authentication(翻译+整理)


1.总览

包括:
  •  user:
  • permissions:二进制的标志,标明是否有权限执行某操作
  • groups:给多个用户打标签和设置权限

2.安装&激活

authentication的支持是作为一个django application,绑定在django.contrib.auth模块中。安装步骤:
  • 在settings.py中的INSTALLED_APPS中,添加django.contrib.auth和django.contrib.contenttypes。
  • run: manage.py syncdb

3.类Class


(1)User

class models.User

Fields

  • username:required
  • first_name:optional
  • last_name:
  • email:
  • password:
  • is_staff:
  • is_active:
  • is_superuser:
  • last_login:
  • date_joined:

Methods

  • is_anonymous():
  • is_authenticated():
  • get_full_name():
  • set_password():
  • check_password():
  • set_unusable_password():
  • has_usable_password():
  • get_group_permissions():
  • get_all_permissions():
  • has_perm():
  • has_perms():
  • has_module_perms():
  • email_user():
  • get_profile():

(2)UserManager

class models.UserManager

Methods

  • create_user():
  • make_random_password():

(3)AnonymousUser

class models.AnonymousUser 

4.基本用法


(1)创建用户

>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')

(2)修改密码

>>> from django.contrib.auth.models import User
>>> u = User.objects.get(username__exact='john')
>>> u.set_password('new password')
>>> u.save()

(3)创建超级用户

manage.py createsuperuser --username=joe --email=joe@example.com

(4)存储用户的附加信息profile

  • 创建自定义类:必须定义一个field去关联User,再定义附加的field:
    from django.contrib.auth.models import User
    
    class UserProfile(models.Model):
        # This field is required.
        user = models.OneToOneField(User)
    
        # Other fields here
        accepted_eula = models.BooleanField()
        favorite_animal = models.CharField(max_length=20, default="Dragons.")
  • 在settings.py中增加配置:
    AUTH_PROFILE_MODULE = 'accounts.UserProfile'
  • 获取profile:get_profile() 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值