如何在Django中间件中忽略媒体和静态URL

时间:2019-01-25 07:43:26

标签: django django-models django-forms django-templates django-views

我正在尝试重定向无权查看该页面的用户。在我的数据库中,我保存了URL名称。示例-company_list

path('company/list', CompanyListView.as_view(), name='company_list'),

现在,我使用的是EXEMPT_URLS,其中保存了URL名称,而这些URL免于用户使用。

EXEMPT_URLS = [
    'login',
    'logout',
    'superadmin_dashboard',
    'admin_dashboard',
]

class PermissionRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):

        assert hasattr(request, 'user')

        current_url = resolve(request.path_info).url_name

        print(request.path_info)

        if request.user.is_authenticated and current_url not in EXEMPT_URLS :
           if request.user.userprofile.user_role_id == 1:
                return redirect('superadmin_dashboard')
            else:
                return redirect('admin_dashboard')

现在问题来了。就像我要添加公司及其徽标一样。当我要去company_list时,它显示的是列表,但没有图像。

"GET /media/user_profiles/logo_L7T5FKg.png HTTP/1.1" 302

我发现了这个问题,当我评论def process_view()时,它在模板中显示图像。但是,当我取消注释时,它不会显示图像。基本上,我的中间件阻止了该"GET /media/user_profiles/logo_L7T5FKg.png HTTP/1.1" 302

该图像网址名称如何放在EXEMPT_URLS

1 个答案:

答案 0 :(得分:0)

基本上,如果用户没有权限,我将重定向到仪表板。因此,在我的中间件MEDIA and STATIC URL中获得了HTTP response status code 302 Found,因为对于MEDIA AND STATIC URL我的自定义中间件也正在运行。因此,无视我发现了request.path

from django.conf import settings
    ...

    MEDIA_URL = request.path.startswith(settings.MEDIA_URL)
    STATIC_URL = request.path.startswith(settings.STATIC_URL)

    if request.user.is_authenticated and current_url not in EXEMPT_URLS and not MEDIA_URL and not STATIC_URL:
        if request.user.userprofile.user_role_id == 1:
            return redirect('superadmin_dashboard')
        else:
            return redirect('admin_dashboard')