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


User對象

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

缺省字段Fields

username

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

first_name
可選。 30 characters or fewer.

last_name
可選。 30 characters or fewer.

email
郵箱,可選。 Email address.

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

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

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

    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.")

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM