【发布时间】:2021-12-17 13:26:11
【问题描述】:
我为我的 Django 项目实现了自定义身份验证设置。用户有一些用户角色。现在我想确保某些特定的路由可能只接受特定的用户角色。假设只有role = 1 的用户才能接受edit/uploaded-files。所以我为此创建了一个中间件。
from django.shortcuts import redirect
class HRMiddleware(object):
def process_request(self, request):
user = request.user
if not (user and user.is_authenticated() and user.email):
return redirect('')
if user.role_id.id != 1:
raise 403
return None
现在我如何才能将此中间件仅应用于某些特定路由?
我找到了一些解决方案,例如使用装饰器@decorator_from_middleware(MyMiddleware)
并在中间件中指定路由。有没有更好的方法来做到这一点?其实我是一个 Laravel 开发者。这是我的第一个 Django 项目。在 laravel 中,我们可以在路由中指定中间件。请帮帮我
【问题讨论】:
标签: python python-3.x django django-middleware