Example of how django restricts access and redirection by anonymous users, while django Anonymous Users

Source: Internet
Author: User

Example of how django restricts access and redirection by anonymous users, while django Anonymous Users

Preface

We should have met that in some pages, we do not want anonymous users to access them, such as personal pages. Such pages can only be accessed by logged-on users. In django, we also have many ways to implement it.

The simplest way is to judge the user is_authenticated in viewz, but this method is also relatively clumsy. We certainly do not want this request to enter our view, before that, a related response can be returned, while django has encapsulated related functions and classes for us. I won't talk much about it below. Let's take a look at the detailed introduction.

Fbv-based login_required

Def login_required (function = None, redirect_field_name = REDIRECT_FIELD_NAME, login_url = None): # In fact, this method also calls is_authenticated to judge pass.

The usage is also simple:

# Fbv mode from django. contrib. auth. decorators import login_required @ login_required def user_info_view (request): # User Interface pass

Therefore, we hope that if anonymous users can redirect to the login interface after accessing this interface, we can set relevant parameters. The login_required modifier will readsettings.LOGIN_URLAnd redirect to this page. If you want to be more flexible, you can also pass related parameters to the decorator.

# Fbv mode @ login_required (login_url = '/login/', redirect_field_name = 'Next') def user_info_view (request): # pass the user's personal interface

Login_url is the Redirection url after anonymous users access it. Generally, it is a login page.

Redirect_field_name is a get request parameter

Assume that the current page will be/user/info/

The redirected url is:/login/?next=/user/info/

This parameter can be used to directly jump back to this page after login, and will be detailed later!

Cbv-based LoginRequiredMixin class

Generally, bloggers use the cbv mode. In this mode, we will rewrite the get and post methods. In theory, we can use the login_required decorators to describe these two methods.

# Cbv mode from django. contrib. auth. decorators import login_requiredfrom django. utils. decorators import method_decoratorclass UserInfoView (View): @ method_decorator (login_required (login_url = '/login/', redirect_field_name = 'Next') def get (self, request ): # obtain the user's personal interface pass

Login_required is a function decorator. method_decorator can convert a function annotator into a method annotator. If there is a post request, we need to write this code again, which seems redundant. Since we use the class to implement it, of course we can achieve it through the advantages of the class! Inherit LoginRequiredMixin!

From django. contrib. auth. mixins import LoginRequiredMixinclass UserInfoView (LoginRequiredMixin, View): def get (self, request): # get User Interface pass

So how does LoginRequiredMixin implement it?

Look at the source code

class LoginRequiredMixin(AccessMixin): def dispatch(self, request, *args, **kwargs):  if not request.user.is_authenticated():   return self.handle_no_permission()  return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)

In fact, it overwrites the dispatch method, because we also inherit the view. In fact, it overwrites the dispatch function in the view. If you know the view logic, you will know why it can be implemented like this!

When we call your view class in the url, suchUserInfoView.as_view()Method, it will calldispatch() This method acts as a distributor. If the get request is used, the get method is called. If the request is a post request, the post method is called. In dispatch, it can certainly be used to determine whether a user is logged on.

Since we only rewrite dispatch, we can also implement it ourselves!

# Custom ingress LoginRequiredMixin (object): @ method_decorator (login_required (login_url = '/login/', redirect_field_name = 'Next') def dispatch (self, request, * args, ** kwargs): return super (LoginRequiredMixin, self ). dispatch (request, * args, ** kwargs)

Of course, do you need to implement it on your own ~

Redirection and redirection

(login_url='/login/', redirect_field_name='next')

These two parameters provide a redirection and Redirection url for us. When an anonymous user logs on to the page to be logged on, it will jump to the login_url. This get request also carries the redirect_field_name parameter, the value is 'Next '.

If he accesses a personal page, he jumps

Http: // 127.0.0.1/login /? Next =/user/info/

We can use this parameter to directly jump to the personal page after logon.

Class LoginView (View): "User Login logic" def get (self, request): # get the next parameter and render it to the template, add an element of the hidden type in the form. next = request. GET. get ('Next', '') return render (request," login.html ", {'Next': next}) def post (self, request): login_form = LoginForm (request. POST) if login_form.is_valid (): user_name = request. POST. get ("username", "") pass_word = request. POST. get ("password", "") next = request. POST. get ('Next', '') user = authenticate (username = user_name, password = pass_word) if user is not None: if user. is_active: login (request, user) if next: # if next exists, go directly to the specified page return HttpResponseRedirect (next) # No jump to the index interface return HttpResponseRedirect (reverse ('index ')) else: return render (request, "login.html", {"msg": "user not activated"}) else: return render (request, "login.html", {"msg ": "username or password error"}) else: return render (request, "login.html", {"login_form": login_form })
# Add <input name = "next" type = "hidden" value = "{next}"/>

Logon redirection on a common page

If a normal page also needs to jump back to the original page after logon, it is very simple. There is a path parameter in the request, which indicates the current page, you only need to include this parameter on the jump to the login interface.

# Template <a class = "loginbtn" href = "/login /? Next = {request. path} "rel =" external nofollow "> logon </a> <a class = 'logoutbtn 'href ="/logout /? Next = {request. path} "rel =" external nofollow "Exit </a> <a class = 'registerbtn 'href ="/register /? Next = {request. path} "rel =" external nofollow "registration </a>

The implementation logic of login is the same as above. In fact, the implementation logic of logout and registration interface is the same.

# logoutclass LogoutView(View): def get(self, request):  next = request.GET.get('next', '')  logout(request)  try:   return HttpResponseRedirect(next)  except:   return HttpResponseRedirect(reverse('index'))

Postscript

This article focuses on the use of the @ login_required modifier and the use and customization of the LoginReqiredMixin class, and finally implement logon redirection and redirection!

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

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.