Django Implements user login access Restrictions @login_required

Source: Internet
Author: User

In the process of website development, we often encounter such requirements: the user login system to access certain pages


If the user does not log in and the direct access will jump to the landing screen, and not access to other pages.


When the user completes the login in the login interface of the jump, automatic access jumps to the previously visited address


To implement such a requirement is simple:

1. @login_required with Django's own decorator.

2. Add @login_required in front of the corresponding view method

3. And configure the Login_url parameter in settings.py

4. Change the form action parameter in LOGIN.HTLM


#views. py

From djanco.contrib.auth.decorators import login_requiredfrom django.shortcuts import Render_to_responsefrom Django.http Import HttpResponse @login_requireddef myview (Request): Return Render_to_response (' index.html ')


#settings. py

.... Login_url = '/accounts/login/' #这个路径需要根据你网站的实际登陆地址来设置 ....

If you want to use Django's default login interface, you can do so by configuring it in urls.py



#urls. py

From django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [url (r ' ^admin/'), admin.site.urls), url (r ' ^, views.index), url (r ' ^accounts/login/, views.acc_login), url (r ' ^logout/, Views.acc_logo UT), url (r ' ^host/, Views.host, name= ' host '), URL (r ' ^asset/, views.asset,name= ' asset '), url (r ' ^audit/, Views.audit , Name= ' audit '),]


#login. html

<div class= "Container" >  <form class= "Form-signin"  action= "/accounts/login/"  method= "POST" >{% csrf_token %} <!--Csrf_token: Generate token-->     


This article is from the "bitter coffee ' s Yun ' an Road" blog, please be sure to keep this source http://alsww.blog.51cto.com/2001924/1732435

Django Implements user login access Restrictions @login_required

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.