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.
# the settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # the Model class Legend(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=300) creator = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now=True) published = models.DateTimeField(null=True, blank=True) available = models.BooleanField(default=False) image = models.ImageField(upload_to='gallery', blank=True, null=True) # the template where i use the img field {% for instance in object_list %} <img style="width: 245px; height: 247px;" src="{{ instance.image.url }}" alt="legend image""> {% endfor %}
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
:
from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # and this one to serve static files: #urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)