Goal: I’m trying to use the same image across all instances of Cause
as a default image
Problem: With the below code, the broken image icon alongside the alt text appears on the page & a 404 error shows in the terminal: [20/Sep/2023 21:48:39] "GET /causes/causes/519d1436-b6e5-4c1c-aa7f-df65d068ef71/images/name-of-image.jpg HTTP/1.1" 404 5022
When I create a Cause instance and then look in the Django admin, this clickable link is shown: Currently: [images/name-of-image.jpg]
but if I click on it, it throws an error that it doesn’t match any URL patterns. Did I misunderstand how to do the MEDIA_URL setting?
I think I could solve this by just directly putting the static image template tag in the templates as desired, but then if I ever wanted to change the image in the future, I’d have to find and change all the template tags. My hope with using the default was to have one location where it can be updated universally. I’ve seen the default=
in ImageFields for Django several times on other resources (StackOverflow etc.) but since I don’t see it in the Django model field doc maybe a default like this is actually not possible?
Questions:
- Can you have a default in an ImageField?
- Did I misunderstand how to do the MEDIA_URL setting?
- Might you please point out anywhere I’m going wrong with this effort?
Project Settings
# Media
MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = "media/"
Model
class Cause(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
cause_representation_image = models.ImageField(upload_to='images', default='images/name-of-image.jpg')
Template
<img src="{{ cause.cause_representation_image }}" alt="cause image">
# I've also tried adding the url too like this:
<img src="{{ cause.cause_representation_image.url }}" alt="cause image">
Thank you in advance!