我根据文件url / path
过滤我的对象时遇到问题我想制作简单的系统,只让员工从特定文件夹(媒体/客户端/文件)下载文件。
我在网址中写了正则表达式,每个请求都转到file_get_url视图,我在文件模型中检查这个文件是否基于url过滤 - 但我不知道如何过滤这个。当我得到对象时,我有" file.url"但不在filter(file_url)中。你知道如何解决这个问题吗?
Urls.py:
urlpatterns = [
url(r'^media/client/files/', 'file.views.file_get_url', name='file_get_url'),
]
Views.py:
@user_passes_test(lambda u: u.is_staff, login_url='/account/login/')
def file_get_url(request):
if request.user.is_staff:
f = File.objects.filter(file_url=request.get_full_path())
return HttpResponse(f.file.url)
Models.py
class File(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.PROTECT, blank=True, null=True)
file = models.FileField(upload_to='client/files/')
type = models.CharField(max_length=32, default=None, blank=True, null=True)
object_id = models.IntegerField(blank=True, null=False, default=None)
content_id = models.IntegerField(default=None, null=False, blank=False)
答案 0 :(得分:0)
我使用两个视图解决了我的问题,一个是基于路径的文件,另一个是基于file_id的。也许对某人会有帮助:))
@user_passes_test(lambda u: u.is_staff, login_url='/account/login/')
def file_get_url(request):
file_path = request.get_full_path()[1:] # to remove '/'
if os.path.isfile(file_path): # to check if this file(based on path) exist there!
response = HttpResponse(FixedFileWrapper(open(file_path, 'rb')), content_type=mimetypes.guess_type(file_path)[0])
response['Content-Length'] = os.path.getsize(file_path)
response['Content-Disposition'] = "attachment; filename=%s" % os.path.basename(file_path)
return response
else:
return HttpResponse('Nothing exist here!')
@user_passes_test(lambda u: u.is_staff, login_url='/account/login/')
def file_get(request, file_id):
f = File.objects.get(id=file_id)
file_path = f.file.url[1:]
response = HttpResponse(FixedFileWrapper(open(file_path, 'rb')), content_type=f.type)
response['Content-Length'] = os.path.getsize(file_path)
response['Content-Disposition'] = "attachment; filename=%s" % os.path.basename(file_path)
return response