如何在Django网页中展示图片?附本人尝试的模板代码示例
Hey there! Let's fix that image display issue in Django. The problem with your current code is that you're using a hardcoded relative path, which Django doesn't handle well out of the box—since it has a specific system for managing static and media files. Here's how to get it working properly:
In your settings.py, make sure these settings are in place (adjust paths if your static folder is located elsewhere):
STATIC_URL = '/static/' # Tells Django where to look for static files at the project root STATICFILES_DIRS = [ BASE_DIR / "static", ]
Move your img folder inside this static directory (so the full path becomes static/img/person_1.jpg).
At the very top of your template file, add this line to enable Django's static file helper tools:
{% load static %}
Replace the hardcoded src attribute with Django's static tag, which automatically generates the correct URL for your static image:
{% for info in chef %} <div class="col-md-3" data-aos="fade-up" data-aos-delay="100"> <img src="{% static 'img/person_1.jpg' %}" alt="Image placeholder" class="img-fluid mb-4 rounded"> <h3 class="mb-3">{{info.name}}</h3> <p class="post-meta text-muted">{{info.title}}</p> <p class="mb-5"></p> </div> {% endfor %}
If each chef has their own unique image stored in your database (instead of a single placeholder), here's how to set that up:
a. Update your Chef model
Add an ImageField to store each chef's image:
from django.db import models class Chef(models.Model): name = models.CharField(max_length=100) title = models.CharField(max_length=100) image = models.ImageField(upload_to='chefs/', blank=True, null=True)
You'll need the pillow library for image handling—install it with:
pip install pillow
b. Configure media files in settings.py
Add these lines to handle user-uploaded media files:
MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media'
c. Add media URL routing
In your project's urls.py, add this to serve media files during development:
from django.conf import settings from django.conf.urls.static import static from django.urls import path urlpatterns = [ # Your existing URL patterns go here ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
d. Update the template for dynamic images
Now you can reference each chef's unique image directly from the model instance:
<img src="{{ info.image.url }}" alt="{{ info.name }}" class="img-fluid mb-4 rounded">
When deploying to production, run python manage.py collectstatic to gather all static files into a single directory that your web server can serve efficiently.
内容的提问来源于stack exchange,提问作者Rude Rude

