Django User Authentication System (1) User object, djangouser

Source: Internet
Author: User

Django User Authentication System (1) User object, djangouser
User object

The User object is the core of the authentication system. User objects are usually used to represent website users and support access control, user registration, and associated creators and content. There is only one user class in the Django Authentication Framework. For example, a Super User ('superusers') or ('staff') user only sets different attributes for the same user object.

Default field Fields

Username

Username, required field. It must be 30 or fewer characters and can contain _, @, +,., and-characters.

First_name
Optional. 30 characters or fewer.

Last_name
Optional. 30 characters or fewer.

Email
Email, optional. Email address.

Password
Password, required. Django does not store passwords in plain text, but stores hash values.

Groups
User Group. Allow-to-associate relationship to Group

User_permissions
User permissions. Allow-to-Allow 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. Determine whether the user can access the admin management interface. The default value is False.

Is_active
Boolean. Whether the user is active. The default value is True. Generally, the is_active of a user is set to False instead of deleting the user.

Is_superuser
Boolean. The default value is False. If this parameter is set to True, all permissions are granted to the user.

    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

The last logon time, which is a datetime object. The default value is the current time.

user.last_login = timezone.now()

Date_joined
Time when the user was created

Method Methods

Is_anonymous ()

Whether it is an anonymous user.

Is_authenticated ()
Whether the user passes the verification and logs in.

Get_full_name ()
Returns first_name plus the last_name, with a space in.

Get_short_name ()
Returns first_name.

Set_password (raw_password)
Set the password.

Check_password (raw_password)
Verify the password.

Get_group_permissions (obj = None)
Returns the set of user group permissions.

Get_all_permissions (obj = None)
Returns all user permissions.

Has_perm (perm, obj = None)
Whether the user has a certain permission. The perm format is "<app label>. <permission codename> ".

Has_perms (perm_list, obj = None)
Whether the user has each permission in the permission list.

Create user

Because the password of the User object is not stored in plaintext, the built-in create_user () method is required to create a User object different from the common Model create object.

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

You can also add users in the admin interface.

Create superusers
$ python manage.py createsuperuser --username=joe --email=joe@example.com
Change Password

Use the built-in set_password () method.

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

Authenticate ()

Verify whether the given username and password are valid users. If valid, a User object is returned. If invalid, None is returned.

from django.contrib.auth import authenticateuser = 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.")

  

 


In django, I wrote admin in the backend. Now I want to use user authentication. I feel that the self-built authentication function is better. How can I use it?

The built-in authentication function is really good, but I don't understand what you mean by using admin, and there are a lot of user authentication items, so I don't know where to start.

If request. user. is_authenticated ():
# Authenticated Users
Else:
# Anonymous Users

Reference: zh.wikibooks.org/..?af=81

When django writes a commercial website, does the user system rewrite it on its own or use its own?

It is best to bring your own, because it is basically enough. If it is not enough, the User model has a get_profile function to get the Profile object associated with the User object. This Profile can have other personal information, most third-party django apps depend on their own users.
In addition, django1.5 also supports User class customization. You can check it out.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.