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

来源:互联网 发布:杭州亚信软件 编辑:程序博客网 时间:2024/06/05 08:09


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 Userclass 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()