You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Django Admin图片预览链接错误致图片无法显示求助

Fixing Duplicate "uploads" Path in Django Image Preview

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/ to uploads/testimonial/, or
  • Re-upload the images through the Admin after making the model change.

Verify the Fix

After making these changes:

  1. Restart your Django development server
  2. 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

火山引擎 最新活动