如何在中间件中设置next_url?

问题描述 投票:0回答:1

我正在为我的 Django 项目编写一个自定义中间件,如果用户尚未确认他们的年龄足以进入页面,它将将每个页面请求重定向到年龄门。当他们确认年龄门时,我希望年龄门页面重定向到他们最初请求的页面。 我的中间件现在如下所示:

from django.shortcuts import redirect

    class AgeGateMiddleware:
        EXCLUDED_URLS = ['/preview/agegate'] 
    
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            if not request.session.get('agegate') and request.path not in self.EXCLUDED_URLS:
                request.session['next_url'] = request.path
                return redirect('/preview/agegate')
    
            response = self.get_response(request)
            return response

我的年龄门视图如下所示:

def age_gate_view(request):

    #Load the original page after checking age gate.
    next_url = request.session['next_url']

    #Register users IP for age gate.
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')

    try:
        ip =ip
    except:
        ip = 'none'

    form = AgeGateForm({'ip':ip})
    
    #Store age gate response
    if request.method == 'POST':
        form = AgeGateForm(request.POST or None,  {'ip':ip})
        if form.is_valid():
            form.save()
            request.session['agegate'] = 'welcome'
            return redirect(next_url)
    
    context = {
        'form':form,
    }

    return render(request,'Academy/agegate.html', context)

现在中间件按预期工作:如果尚未确认,它会重定向到年龄门。但是: next_url 似乎不起作用,因为它不断重定向到

projectpage/favicon.ico
而不是原始请求的页面。 我做错了什么?

django django-views middleware django-middleware
1个回答
0
投票

您似乎遇到了 next_url 设置不正确或未按预期工作的问题。该问题可能与 favicon.ico 请求也被您的中间件拦截这一事实有关,从而导致错误的重定向。

解决此问题的一种方法是排除静态文件(包括图标)由中间件处理。您可以修改 AgeGateMiddleware 以跳过某些路径,例如静态文件的路径。这是中间件的更新版本,其中包含静态文件检查: 从 django.shortcuts 导入重定向 从 django.urls 导入 is_valid_path

AgeGateMiddleware 类: EXCLUDED_URLS = ['/预览/agegate']

def __init__(self, get_response):
    self.get_response = get_response

def is_static_file(self, path):
    # Check if the path is for a static file
    return path.startswith('/static/') or path.startswith('/media/')

def __call__(self, request):
    if not request.session.get('agegate') and request.path not in self.EXCLUDED_URLS:
        # Check if the request path is a valid path (not a static file)
        if not self.is_static_file(request.path) and is_valid_path(request.path):
            request.session['next_url'] = request.path
            return redirect('/preview/agegate')

    response = self.get_response(request)
    return response

在这个修改后的中间件中:

我添加了 is_static_file 方法来检查给定路径是否对应于静态文件。您可以根据项目的设置调整此方法中的路径。 我在设置 request.session['next_url'] 之前添加了对 is_static_file(request.path) 的检查。 通过从重定向逻辑中排除静态文件,您应该在重定向到年龄门时设置更准确的 next_url,并且它应该按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.