简体   繁体   中英

Not able to access media file even if file exists when checked manually

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM