I’m actually new to django and I found a problem when loading my images, I did the settings like the docs said and it saves my images to the right folder. Just the loading part does not work as I want it to.
JavaScript
x
20
20
1
# the settings.py
2
STATIC_URL = '/static/'
3
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
4
MEDIA_URL = '/media/'
5
6
# the Model
7
class Legend(models.Model):
8
name = models.CharField(max_length=100)
9
description = models.CharField(max_length=300)
10
creator = models.ForeignKey(User, on_delete=models.CASCADE)
11
created = models.DateTimeField(auto_now=True)
12
published = models.DateTimeField(null=True, blank=True)
13
available = models.BooleanField(default=False)
14
image = models.ImageField(upload_to='gallery', blank=True, null=True)
15
16
# the template where i use the img field
17
{% for instance in object_list %}
18
<img style="width: 245px; height: 247px;" src="{{ instance.image.url }}" alt="legend image"">
19
{% endfor %}
20
the upload is working as expected. Saves all images to the media folder (which is on the applevel) so: media/gallery/name.jpg. running the server doesnt show the image but the source seems fine: http://127.0.0.1:8000/media/gallery/gto.jpg
There seems to be a problem with serving files locally when debugging, but all i could find were for older django versions. Iam using django –version 2.2.
I appreciaty any help
Advertisement
Answer
When you are running django under DEBUG = True
, you should also add media urls:
Add this to end of your main urls.py
:
JavaScript
1
8
1
from django.conf import settings
2
from django.conf.urls.static import static
3
4
if settings.DEBUG:
5
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
6
# and this one to serve static files:
7
#urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
8