When combining django and nginx The method is to extract static files such as images with collectstatic and place them in nginx.
However, if you place it in ** nginx, you can see the static files without logging in to the system **, so ** This method can be used with the requirement that you want to deliver images that you want to limit to logged-in users **.
nginx → uwsgi → django You can access django from nginx.
How to create a view for an image URL in django. Since it goes through django's view, you can only access it by logging in to the system.
projectroot
+ projectname
+ settings.py
+ media
+ pictures
+ test.jpg
+ testapp
+ urls.py
+ views.py
Define a view to access files in media in an application in django called testapp.
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
views.py
from django.http import HttpResponse
import os
from projectname import settings
def picture(request, imgfilename):
file_path = os.path.join(settings.MEDIA_ROOT , 'pictures/' + imgfilename)
with open(file_path, "rb") as f: #rb stands for read binary
imgfile = f.read()
return HttpResponse(imgfile , content_type="image/jpeg")
urls.py
urlpatterns = [
path('media/<imgfilename>', views.picture, name='picture'),
]
http://localhost:ポート/testapp/media/test.jpg
Recommended Posts