Django Registration, login, and third-party interface programs (1): basic knowledge

Source: Internet
Author: User

I. Overview

Django has a set of registered login modules, the AUTH system contains the following:

Users
Permission
Group
Message

In the settings.py configuration, the following configuration is indispensable

MIDDLEWARE_CLASSES = (‘django.middleware.common.CommonMiddleware‘,‘django.contrib.sessions.middleware.SessionMiddleware‘,‘django.contrib.auth.middleware.AuthenticationMiddleware‘,‘django.contrib.messages.middleware.MessageMiddleware‘,)INSTALLED_APPS = (‘django.contrib.auth‘, ‘django.contrib.contenttypes‘,  ‘django.contrib.sessions‘,  ‘django.contrib.sites‘,‘django.contrib.messages‘,)

These are typically generated automatically when the Django project is created, and the manage.py syncdb corresponding tables are generated by the run.

Ii. Users

Field
class models.User
specific fields for the user object reference: Django official website Documentation
Note Here is_active is whether the user is active, for the removal of users as far as possible to set it as false not a real delete, but also as a decision whether to log in.
Method
Read more about Django official website documentation
Here are a few key learning points.
1, is_anonymous() : Distinguish between anonymous users and users can be logged in the method, often used is_authenticated() .
2, is_authenticated() : authenticated indicates that it has been verified, then this method is that it only indicates that the user provides a valid user name and password.
3, set_password(raw_password) : Change the password, and automatically process the hash value
4, check_password(raw_password) : Check the password is correct

Iii. Management methods (Manager functions)

class models.UserManager
1 create_user(username, email, password=None) : Create, save and return a user,username,email and password are set to the given value, and user sets the Is_active=true.
2. make_random_password() :
Returns a random password for the given value and length:

make_random_password(length=10,allowed_chars=‘abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789‘)
Iv. Basic Usage

1. Create user
Use create_user() to create a user, as follows:

from django.contrib.auth.models import Useruser = User.objects.create_user(‘BeginMan‘,‘abcd123‘,‘[email protected]‘)print user.is_staff #Trueuser.save()

2. Change your password
Use set_password() to make changes

v. Authentication in Web Requests

Detailed content Reference
1. Basic overview

First, install the Sessionmiddleware and Authenticationmiddleware middleware. Add them to the middlewareclasses settings. Once you've installed these middleware, you'll be able to access request.user in the view. Request.user will return a user object for the currently logged-on users. If no user is currently logged on, Request.user will return an instance of the Anonymoususer object. You can useis authenticated () to determine if a user is logged in, as follows:

if request.user.is_authenticated(): #已登录用户else: #匿名用户

2. User Login
Django provides 2 functions in Django.contrib.auth: authenticate() and login() .
authenticate() : Authentication function :

If you are authenticating with a given user name and password, use the Authenticate () function. He receives 2 parameters, one is username and the other is password. If the authentication succeeds, it returns a user object. If the password is not valid, it returns a none. For example:

from django.contrib.auth import authenticateuser=authenticate(username=‘john‘,password=‘secret‘)ifuserisnotNone:print"用户名、密码正确!"else:print"用户名、密码错误!"

login(): Login function

Use the login () function to log in to a user in the view. It receives the HttpRequest object and a user object . Login () Saves the user's ID to the session through the Django session framework.

from django.contrib.auth import authenticate, logindef my_view(request):    username = request.POST[‘username‘]    password = request.POST[‘password‘]    user = authenticate(username=username, password=password)    if user is not None:        if user.is_active:            login(request, user)            # Redirect to a success page.        else:            # Return a ‘disabled account‘ error message    else:        # Return an ‘invalid login‘ error message.

3. User log Out
To log out of use
Django.contrib.auth.login () can be used in the view if the user is logged in
Django.contrib.auth.logout (). It receives a HttpRequest parameter with no return value. For example:

from django.contrib.auth import logout def logout_view(request):    logout(request)    #转到成功页面

Please note: If the user is not logged in, logout () will not throw any exceptions.

Vi. restricting access to users

1. Original method
The original method is redirection
Such as:if not request.user.is_authenticated():
2. Using login_required() Decorators

Decorators.loginrequired ([redirectfieldname=redirectField_name])
The procedure is as follows:

from django.contrib.auth.decorators import login_required@login_requireddef my_view(request):   ...

login_required()Principle:

If the user is not logged in, redirect to Settings. Login_url.
Normal execution if the user is already logged in.

3. The logged-in user has passed the pass test (passtest) to restrict access
See official documentation

vii. Authority (Permissions)

django comes with a simple permission system. It provides a way to pay permissions to users and user groups. It is used in the Django Admin site, and you can use it in your own code, of course. The Django Admin site applies permissions like this:
via "add" Permissions to control whether users can access the Add form and add an object of the specified type. The Change permission controls whether the user can access the list of objects of the specified type and modify the form. * Use the Delete permission to control whether the user can delete objects of the specified type.
permissions are assigned to each type of object, not to a specific instance of the object. You can say "Mary can change the new story (stories)", but you can't say "Mary can modify the new story she created" or "Mary could only modify a specific state of a particular release time, a specific ID of the story, and so on." These features are currently under discussion by Django developers.

1, default permissions
3 Basic permissions-Add, create, and delete-are created automatically when you create a Django model that includes a classadmin of your own. After the surface phenomenon, when you run MANAGE.PYSYNCDB, these permissions are added to the Auth_permission data table.
Please note that if you don't have classadmin in your model, These permissions are not created when you run MANAGE.PYSYNCDB. If you want to add these permissions after you initialize the database, you can include class admin in the model and then run the manage.pysyncdb once.
2, custom permissions
Span style= "font-family: ' Microsoft Yahei '; font-size:13px; " > In order to customize permissions for the specified model, you can use the Modelmetaattribute of permissions (permissions). This example creates 3 custom permissions.

class Task(models.Model):    ...    class Meta:        permissions = (            ("can_view", "Can see available tasks"),            ("can_change_status", "Can change the status of tasks"),            ("can_close", "Can remove a task by setting its status as closed"),        )

The next thing to do is run SYNCDB to create these permissions.
3. Permission API

Name: Must. is less than or equal to 50 characters. For example: ' Canvote '.
ContentType: Must. Referenced from the Djangocontenttype data table, which contains the installed
The type of the Django model.
Codename: Must. is less than or equal to 100 characters. Example: ' Can
vote '

VIII. Certification data in the template

If used RequestContext , the user and permission objects of the logged-in users are saved in the template context.
1, User (users)
The currently logged on user, whether anonymous or otherwise, is stored in the template variable {{user}} . Such as:

{%ifuser.is_authenticated%}  <p>欢迎,{{user.username}}。谢谢您的来访。</p>{%else%}  <p>欢迎,请登录。</p>{%endif%}

2. Permissions (Permissions)
The permissions of the currently logged on user are stored in the template variable {{perms}} , which is django.core.context_processors_PermWrapper the instance.
In the {{perms}} object, the lookup for a single property is using the User.hasmoduleperms. In the following example, if the user has any permissions on the Foo app, it returns true. {{Perms.foo}}
Second-level attribute lookups are using User.hasperm. In the following example, if the user has Foo.canvote permission, it returns true. {{Perms.foo.can_vote}} So you can judge permissions in the template with the {%if%} statement

{%ifperms.foo%}<p>你有操作foo的权限。</p>{%ifperms.foo.can_vote%}<p>你可以投票。</p>{%endif%}{%ifperms.foo.can_drive%}<p>你可以开车。</p>{%endif%}{%else%}<p>你没有操作foo的权限。</p>{%endif%}
ix. Group (Groups)

Groups are typically used to categorize users so that you can apply permissions or label other tags to users within those groups. A user can belong to any number of groups.
The user in the group automatically gets the permissions assigned to the group. For example, if the group Siteeditors has the permissions of the canedithome_page, then any user who joins the group will automatically have this permission.
Groups are also a convenient way of categorizing users and labeling or extending them. For example, if you create a ' specialusers ' group, you can write code that allows them to visit the members area of the site or send them to email that is dedicated to their members.

Django Registration, login, and third-party interface programs (1): basic knowledge

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.