在继承了django的LoginRequiredMixin的View中,当未登录访问时,不要附加”next”参数来重定向到登录URL

總結

可以创建一个继承了LoginRequiredMixin的自定义类,通过重写handle_no_permission函数来实现重定向部分,以避免传递next参数。

前提

    • 使用モジュールの各バージョンは以下です

Django 3.2.19

确认现象

继承了LoginRequiredMixin的Django视图,如果未登录就访问,将会被重定向到登录URL。此时,URL中会添加一个名为”next”的查询参数,以便在登录后能够返回重定向之前的视图。


# 未ログインでLoginRequiredMixin継承したViewにアクセスしたときにリダイレクトされるURL
LOGIN_URL = '/loginform'

from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView

# このviewのルーティングは「/myapp/Index」
class IndexView(LoginRequiredMixin, TemplateView):
    template_name = "myapp/index.html"
nextパラメータ01.png

造成这个结果的原因是什么?

这是由于LoginRequiredMixin的规格要求。

基于原因的解决方法

我认为改变LoginRequiredMixin的规范本身是困难的。因此,我将准备一个继承自LoginRequiredMixin的Mixin类,并进行自定义修改。
更具体地说,在Mixin自定义类中,我将重写handle_no_permission函数,以防止附加“next”参数。

步驟

在应用程序文件夹中创建一个新的.py文件,并准备以下自定义Mixin类。

from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect

class CustomLoginRequiredMixin(LoginRequiredMixin):
    def handle_no_permission(self):
        if self.raise_exception or self.request.user.is_authenticated:
            return super().handle_no_permission()
        else:
            return redirect(self.get_login_url())

接下来,我们将继承一个已创建的Mixin类,该类对不带有”next”参数的View进行操作。

from django.shortcuts import render
#from django.contrib.auth.mixins import LoginRequiredMixin カスタムクラスを使用するため不要
from django.views.generic import TemplateView

from .mixins import CustomLoginRequiredMixin #追加

# このviewのルーティングは「/myapp/Index」
class IndexView(CustomLoginRequiredMixin, TemplateView):
    template_name = "myapp/index.html"

从现在开始,将不再添加“next”参数。

nextパラメータ02.png

就是这样。

请谅解,我只能提供英文的回答。如果你有什么其他问题,我会尽力帮助你。

(Sorry, I can only provide the answer in English. If you have any other questions, I will do my best to assist you.)

 

bannerAds