How to display an image as the current value to an ImageField in a DJango app
I have this form in a Django template:
<form action="{% url 'MCARS:Service-Record' %}" method="POST">
{% csrf_token %}
<div class="box-body">
{% for field in form %}
{% if not forloop.counter|divisibleby:2 %}
<div class="row">
{% endif %}
<div class="col-md-6">
<div class="mb-3 form-element form-control">
{{ field.label_tag }}
{% if field.errors %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
{% endif %}
{% if field.ClearableFileInput %}
<div>
<p>Current Image:</p>
<img src="{% static form.instance.avatar.url %}" alt="Uploaded Image" style="max-width: 300px; height: auto;">
</div>
{% endif %}
{{ field|add_class:'form-control' }}
</div>
</div>
{% if forloop.counter|divisibleby:2 %}
</div>
{% endif %}
{% endfor %}
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary mt-2"><i class="mdi mdi-content-save"></i> Save</button>
</div>
</form>
using this Model,
lass Profile(models.Model):
# Managed fields
user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA)
bio = models.TextField(null=True, blank=True)
avatar = models.ImageField(upload_to="static/MCARS/img/members", null=True, blank=True)
birthday = models.DateField(null=True, blank=True)
gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True)
and this form
class UserProfileForm(ModelForm):
class Meta:
model = Profile
exclude = ('user','memberId','invited', 'registered')
There is one field in there called avatar. I get to this one part in the template:
{% if field.ClearableFileInput %}
<div>
<p>Current Image:</p>
<img src="{% static form.instance.avatar.url %}" alt="Uploaded Image" style="max-width: 300px; height: auto;">
</div>
{% endif %}
and I cannot get the image to display. What am I missing?
Thanks!
First of all {% static %}
is for static files (like CSS/JS), not for media uploads like images uploaded by users.
Secondly,
field.ClearableFileInput
does not evaluate correctly like that. Instead, check the field name (field.name
) or specifically the avatar
field.
update the block in your template:
{% if field.name == "avatar" and form.instance.avatar %}
<div>
<p>Current Image:</p>
<img src="{{ form.instance.avatar.url }}" alt="Uploaded Image" style="max-width: 300px; height: auto;">
</div>
{% endif %}
make sure you have the following setup in settings.py and urls.py file.
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... your other urls ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# Don't store media inside static/ change it to-
avatar = models.ImageField(upload_to="MCARS/img/members", ...)