Home > front end >  Not able to access media file even if file exists when checked manually
Not able to access media file even if file exists when checked manually

Time:01-08

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.

Info

  1. Language: Python [v.3.9.7]
  2. Platform: Django [v.3.2.8]

Goal

Being able to access the media file

Description

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?

CodePudding user response:

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
  •  Tags:  
  • Related