Why Django can't find image on this path?
Question:
So. This is my first Django project. I am using Django Admin template to add/edit/delete content.
I added option to add image to specific section. Here is the model
class Project(models.Model):
title = models.CharField(max_length = 100)
description = models.TextField()
technology = models.CharField(max_length = 20)
image = models.ImageField(upload_to = "projects/images/")
And it works. It creates images directory inside project directory which can be found in root directory.
When I load image in template I load it with
<img src="/{{project.image.url}}" alt="" class="card-img-top">
Then in HTML it creates element
<img src="/projects/images/106780.jpg" alt="" class="card-img-top">
But inn console it says that it can’t find image on
http://127.0.0.1:8000/projects/images/106780.jpg
My directory has this hierarchy
portfolio
|
|__ blog
|__ projects
|__ __pycache__
|__ images
|__ migrations
|__ templates
|__ ...
|__ venv
|__ db.sqlite3
|__ manage.py
Answers:
Here you are using static path for image
<img src="/{{project.image.url}}" alt="" class="card-img-top">
<img src="/projects/images/106780.jpg" alt="" class="card-img-top">
You need to use dynamic path so that server can understand full path of the image.
<img src="{% get_media_prefix %}{{project.image.url}}" alt="" class="card-img-top">
Hope this can solve your problem.
For more infor visit official doc Django version 2.2 – media path
if you’re working with forms, make sure to add "enctype"
So. This is my first Django project. I am using Django Admin template to add/edit/delete content.
I added option to add image to specific section. Here is the model
class Project(models.Model):
title = models.CharField(max_length = 100)
description = models.TextField()
technology = models.CharField(max_length = 20)
image = models.ImageField(upload_to = "projects/images/")
And it works. It creates images directory inside project directory which can be found in root directory.
When I load image in template I load it with
<img src="/{{project.image.url}}" alt="" class="card-img-top">
Then in HTML it creates element
<img src="/projects/images/106780.jpg" alt="" class="card-img-top">
But inn console it says that it can’t find image on
http://127.0.0.1:8000/projects/images/106780.jpg
My directory has this hierarchy
portfolio
|
|__ blog
|__ projects
|__ __pycache__
|__ images
|__ migrations
|__ templates
|__ ...
|__ venv
|__ db.sqlite3
|__ manage.py
Here you are using static path for image
<img src="/{{project.image.url}}" alt="" class="card-img-top">
<img src="/projects/images/106780.jpg" alt="" class="card-img-top">
You need to use dynamic path so that server can understand full path of the image.
<img src="{% get_media_prefix %}{{project.image.url}}" alt="" class="card-img-top">
Hope this can solve your problem.
For more infor visit official doc Django version 2.2 – media path
if you’re working with forms, make sure to add "enctype"