Reputation: 743
I have a media file that Django isn't able to access, even if it definitely exists if I enter its URL in the browser.
Being able to access the media file
The thing is, people can upload books on my website. People upload images of these books in different sizes, so I want to be able to handle all of them, so I access the width and height of the image and then use that as the size of the image in the view (CSS). To do that, I've used a custom filter image_size
that is going to do all the work of accessing the image and finding its size, which I send back to the view:
@register.filter
def image_size(img, host):
img = host[0] + "://" + host[1] + img
with Image.open(img) as image:
width, height = image.size
dct = {
"width": width,
"height": height
}
return dct
Here, host[0]
is the protocol (request.scheme
) of the URL of the image and host[1]
is the host name (request.get_host()
). Here's my view:
def all_books(request):
if request.user.is_authenticated:
context = {
"books": Book.objects.all(),
"request": request,
"user_profile": UserProfileInfo.objects.get(user=request.user),
"mail_sent": False,
}
else:
context = {
"books": Book.objects.all(),
"request": request,
"mail_sent": False,
"user_profile": False,
}
context["host"] = [request.scheme, request.get_host()]
if request.GET.get("context") == "mail_sent":
context["mail_sent"] = True
return render(request, 'main/all_books.html', context)
settings.py static and media config:
STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR,]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_URL = '/main/user_login/'
Where BASE_DIR
is Path(__file__).resolve().parent.parent
(Path
is imported from pathlib
)
I haven't done collectstatic
because for some reason it removes connection to CSS and suddenly no CSS is rendered.
What should I do to get it working?
Upvotes: 1
Views: 227
Reputation: 3717
Uploaded files go to MEDIA_ROOT unless it is defined differently in the model field You build the path to the img file "manually" in the filter ... which does not point to media/...
img = host[0] + "://" + host[1] + img
I do not know what you hand in as 'img' but here it looks like the string is just
img = "https://my_serverm_image"
But on the server you need lokal path depending on your operating system e.g. c:/my_project/media on windows. That path is stored in settings.MEDIA_ROOT. So a correct string could be:
img = settings.MEDIA_ROOT + img
Upvotes: 1