Home > Mobile >  Can't load local images with HTML
Can't load local images with HTML

Time:07-15

I am developing a simple site with Django, and wanted to load some images locally to some pages. But it doesn't load for some reason. I know there are similar questions, and from what I understand;

a-) It can be a directory problem, html file and img file is in the same directory. Still doesn't work; directory, and the html file. I tried moving the img.jpg to the templates/images directory and try <img src="images/img.jpg" height="400" width="374"> within the html file but that didn't work either.

b-) It could be a typo, but from the images up there that shouldn't be the case either.

c-) Files could be corrupted, I can open the image with browsers and tried using different images too.

d-) Img could be restricted, but that is not the case either. I think.

Trying to fix this for two days now, thought for some reason usage of extend or block might cause some problems and tried without them, still no good. and as I said its only a problem with local files. Can use files with direct link.

CodePudding user response:

settings.py
# add this to your settings.py
import os

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

Then create a folder named static inside your app's folder. Then create another folder with the same name as your app inside that static folder.

The resulting structure should be: your_project_name/your_app_name/static/your_app_name/

You can also create a folder named images inside that last folder.

The resulting structure should be: your_project_name/your_app_name/static/your_app_name/images/

Place your image (let's call it my_image.jpg) insite that images folder.

Now in your template you can use the static tag:

{% load static %}
...
<img src="{% static 'your_app_name/images/my_image.jpg' %}" alt="">

More info here: https://docs.djangoproject.com/en/4.0/howto/static-files/

CodePudding user response:

django serve html with views:

class MyTemplateView(TemplateView):
    template_name = 'my.html'

for template in Django exists template settings. https://docs.djangoproject.com/en/4.0/ref/settings/#std-setting-TEMPLATES templates should be in special folder.

Images Django takes from media or static settings. https://docs.djangoproject.com/en/4.0/ref/settings/#media-root images should be in special folder.

Try configuring your project accordingly for Django-Project.

  • Related