在此视图下,我在加载媒体文件之前先检查用户是否已登录
from django.urls import path, include, re_path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.decorators import login_required
from django.views.static import serve
### require login for showing media
## todo restrict to specific patterns ? e.g. an authenticated user can only access
## files in his own folder
@login_required
def protected_serve(request, path, document_root=None, show_indexes=False):
return serve(request, path, document_root, show_indexes)
urlpatterns = [
path('', views.home, name='home'),
re_path (r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:], protected_serve, {'document_root': settings.MEDIA_ROOT}),
]
我想要实现的是检查用户仅访问具有自己用户名的文件夹,例如用户“ FOO”只能访问媒体子文件夹中具有相同名称的文件。