Django用戶認證系統(一)User對象

User對象

User對象是認證系統的核心。用戶對象一般用來表明網站的用戶,並支持例如訪問控制、註冊用戶、關聯建立者和內容等。在Django認證框架中只有一個用戶類,例如超級用戶('superusers’)或('staff')用戶只不過是相同用戶對象設置了不一樣屬性而已。python

缺省字段Fields

usernamedjango

用戶名,必需字段。30個字符或更少,能夠包含 _, @, +, . 和 - 字符。app

first_name
可選。 30 characters or fewer.框架

last_name
可選。 30 characters or fewer.ide

email
郵箱,可選。 Email address.網站

password
密碼,必需。Django不是以明文存儲密碼的,而是存儲哈希值。this

groups
用戶組。Many-to-many relationship to Groupspa

user_permissions
用戶權限。Many-to-many relationship to Permissioncode

    groups = models.ManyToManyField(Group, verbose_name=_('groups'),
        blank=True, help_text=_('The groups this user belongs to. A user will '
                                'get all permissions granted to each of '
                                'their groups.'),
        related_name="user_set", related_query_name="user")
    user_permissions = models.ManyToManyField(Permission,
        verbose_name=_('user permissions'), blank=True,
        help_text=_('Specific permissions for this user.'),
        related_name="user_set", related_query_name="user")

is_staff
Boolean。決定用戶是否能夠訪問admin管理界面。默認False。對象

is_active
Boolean。 用戶是否活躍,默認True。通常不刪除用戶,而是將用戶的is_active設爲False。

is_superuser
Boolean。默認False。當設爲True時,用戶得到所有權限。

    def has_perm(self, perm, obj=None):
        """
        Returns True if the user has the specified permission. This method
        queries all available auth backends, but returns immediately if any
        backend returns True. Thus, a user who has permission from a single
        auth backend is assumed to have permission in general. If an object is
        provided, permissions for this specific object are checked.
        """

        # Active superusers have all permissions.
        if self.is_active and self.is_superuser:
            return True

        # Otherwise we need to check the backends.
        return _user_has_perm(self, perm, obj)

last_login

上一次的登陸時間,爲datetime對象,默認爲當時的時間。

user.last_login = timezone.now()

date_joined
用戶建立的時間

方法Methods

is_anonymous()

是不是匿名用戶。

is_authenticated()
用戶是否經過驗證,登錄。

get_full_name()
返回first_name plus the last_name, with a space in between.

get_short_name()
返回first_name.

set_password(raw_password)
設置密碼。

check_password(raw_password)
驗證密碼。

get_group_permissions(obj=None)
返回用戶組權限的集合。

get_all_permissions(obj=None)
返回用戶全部的權限集合。

has_perm(perm, obj=None)
用戶是否具備某個權限。perm的格式是 "<app label>.<permission codename>". 

has_perms(perm_list, obj=None)
用戶是否具備權限列表中的每一個權限。

建立用戶

因爲User對象的密碼不是明文存儲的,因此建立User對象時與一般的Model create不一樣,需用內置的create_user()方法。

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

# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()

固然也能夠在admin界面中添加用戶。

建立superusers

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

修改密碼

使用內置的set_password()方法。

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

驗證用戶

authenticate()

驗證給出的username和password是不是一個有效用戶。若是有效,則返回一個User對象,無效則返回None。

from django.contrib.auth import authenticate
user = authenticate(username='john', password='secret')
if user is not None:
    # the password verified for the user
    if user.is_active:
        print("User is valid, active and authenticated")
    else:
        print("The password is valid, but the account has been disabled!")
else:
    # the authentication system was unable to verify the username and password
    print("The username and password were incorrect.")
相關文章
相關標籤/搜索