# settings.py
MEDIA_ROOT_FOR_SENSITIVE_FILES = '/path/to/your/special/folder'
# models.py
from functools import partial
from django.db import models
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.http import FileResponse
from django.http.response import Http404
from django.db.models import FileField
# Create a custom storage location, using a value from your settings file
sensitive_upload_storage = FileSystemStorage(location=settings.MEDIA_ROOT_FOR_SENSITIVE_FILES,
base_url='/some_prefix/')
# ... and a file field that will use the custom storage
AuthenticatedFileField = partial(FileField, storage=sensitive_upload_storage)
class UserUpload(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING)
file = AuthenticatedFileField()
# views.py / handles the url "/some_prefix/{PATH}".
def download_userupload(request, path):
try:
file = UserUpload.objects.filter(user=request.user, file=path)
except UserUpload.DoesNotExist:
return Http404
return FileResponse(file.file)
1条答案
按热度按时间ndasle7k1#
我不确定我的方法是不是最聪明的,但是我通常会在有文件字段的模型中添加一个用户字段。然后,在返回文件的基于函数的视图中,我执行一个检查,看看
request.user
是否是同一个用户。另外,对于像这样的文件,我确保使用FileSystemStorage
类沿着FileField
类将它们存储在一个不可公开访问的目录中。下面是几个片段来说明我自己的方法:
希望这对你有帮助,如果你有任何进一步的问题,我很乐意跟进!