Django Admin图片预览链接错误致图片无法显示求助
Hey there, let's get that image preview working properly! The issue here is a duplicate "uploads" segment in your image URL, which is happening because of how you've configured upload_to and MEDIA_ROOT together.
What's Causing the Problem?
Your ImageField uses upload_to='uploads/testimonial', and your MEDIA_ROOT is set to BASE_DIR/uploads/. When Django saves the image, it combines these two paths:
- Actual file path you intended:
myapp/mysite/uploads/testimonial/image.jpg - Path Django is using:
BASE_DIR/uploads/uploads/testimonial/image.jpg - Generated preview URL:
MEDIA_URL + upload_to path→/uploads/uploads/testimonial/image.jpg
This mismatch is why the image won't load—Django is looking for the file in a nested uploads/uploads folder that doesn't match where you've stored it.
Step-by-Step Fixes
1. Correct the upload_to Path in models.py
Since upload_to is relative to MEDIA_ROOT, you don't need to include "uploads" here. Update your ImageField to:
class Testimonial(models.Model): def __str__(self): return self.title TESTIMONIAL_STATUS = ((1, 'Active'), (0, 'Inactive')) title = models.CharField(max_length=255) description = HTMLField() image = models.ImageField(upload_to='testimonial') # Removed "uploads/" prefix status = models.PositiveSmallIntegerField(choices=TESTIMONIAL_STATUS, default=1) published_date = models.DateTimeField(auto_now_add=True, blank=True)
This will make Django save images directly to MEDIA_ROOT/testimonial/, which matches your existing file path.
2. Add Media URL Routing to urls.py
Django doesn't automatically serve media files in development mode. You need to add this to your project's main urls.py:
from django.conf import settings from django.conf.urls.static import static from django.urls import path import views urlpatterns = [ path('', views.index, name='index'), ] # Serve media files in development environment if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This tells Django to map requests to /uploads/ directly to your MEDIA_ROOT folder.
3. Fix Existing Image Files (If Needed)
If you already have images uploaded with the old path, either:
- Manually move the files from
uploads/uploads/testimonial/touploads/testimonial/, or - Re-upload the images through the Admin after making the model change.
Verify the Fix
After making these changes:
- Restart your Django development server
- Go to the Testimonial Admin page, edit an entry, and click the image preview link—it should now point to
http://127.0.0.1:8000/uploads/testimonial/image.jpg, which matches your actual file location.
内容的提问来源于stack exchange,提问作者Nikul Panchal




