目前遇到的狀況是
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
models.py
class UserUploader(models.Model):
uploader = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='上傳者')
upload_lesson = models.ForeignKey(Lesson, verbose_name='課程', on_delete=models.CASCADE)
upload_files = models.FileField(verbose_name='上傳證明', upload_to='user_upload/%Y/')
upload_date = models.DateTimeField(verbose_name='最後上傳日期', auto_now=True)
def __str__(self):
return self.uploader.username
目前上傳者上傳檔案後 upload_files會產生一個類似 http://localhost:8000/media/user_upload/2024/ithome.png 的網址
但是這個網址是任何人只要知道連結都可以查看的
想請問要如何限制特定User登入後才能查看網址 否則一律跳轉到home呢
有試著在urls.py中做一些限制 但還是沒效果
path('media/user_upload/<str:status>', media_access, name='media'),
謝謝大家
# models.py
class UserUploader(models.Model):
upload_files = models.FileField(verbose_name='上傳證明', upload_to='user_upload/%Y/')
# urls.py
# 不要在後面加 static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# 部署時也不要在Nginx那邊處理MEDIA_ROOT的相關設定
urlpatterns = [
path('media/<str:filename>/', download),
...
]
# views.py
from django.http import HttpResponseNotFound, FileResponse
from .models import UserUploader
from django.contrib.auth.decorators import login_required
@login_required
def download(req, filename):
try:
f = UserUploader.objects.get(upload_files=filename)
res = FileResponse(f.upload_files.file)
res['Content-Type'] = 'application/octet-stream'
res['Content-Disposition'] = f'attachment;filename="{f.upload_files.name}"'
return res
except:
return HttpResponseNotFound("無此檔案")
簡單的說就是原本是會serve一個資料夾的全部,改成動態的去返回一個file而已。
非常感謝!
確實應該要靈活運用
這幾天困擾的是
路徑要加上自己設定的user_upload
UserUploader.objects.get(upload_files='user_upload/' + filename)
你要存在不同的地方?
https://docs.djangoproject.com/en/5.0/ref/models/fields/#filefield
filefield有個參數叫 storage,用來存下面的 FileSystemStorage 實例,就是用來改存放位置或存放的媒體的。
https://docs.djangoproject.com/en/5.0/ref/files/storage/#django.core.files.storage.FileSystemStorage