I'm learning Django, and I've spent a week+ trying to display images in my app. I think that there's an issue with my settings but I'm perplexed since the static files are loading, though the images with similar settings are not.
What confuses me so much is that my static files are loaded ok at MEDIA_ROOT/static, but that image files aren't found at MEDIA_ROOT/media. Based on settings.py, static seems like it would live at
# C:\Users\...\final\static
but it's clear that this isn't true.
structure
├── final
│ ├── dogtracks
│ │ ├── static
| │ │ ├── dogtracks
│ ├── media
| │ ├── images
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # C:\Users\...\final\media
models.py
class Animal(models.Model):
...
photo = models.ImageField(upload_to='images', null=True, blank=True)
...
class AnimalForm(ModelForm):
class Meta:
model = Animal
fields = ['name', 'breed', 'species', 'birthday', 'photo']
html
{% if pet.photo %}
<img src="final{{ pet.photo.url }}" />
{% else %}
<img src="{% static 'dogtracks/noun-pet.png' %}" />
{% endif %}
I've read dozens of answers here on SO and gone through tutorials online. I've moved the location of my images folder to try to show these images.
Add path of MEDIA_URL
and MEDIA_ROOT
in urls.py of project directory
urlpatterns = [
path("", include("myapp.urls")),
path('admin/', admin.site.urls),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Add this