Skip to main content
 首页 » 编程设计

python之无法使用 MEDIA_ROOT 和 MEDIA_URL 在 Django 中上传图片

2025年05月04日34me-sa

你好,我想在 admin django 中上传图片,但是当我使用 media_root 和媒体 url 时,图片无法上传。这是模型.py

class Product(models.Model): 
    category        = models.ForeignKey('Category') 
    userprofile     = models.ForeignKey('UserProfile') 
    title           = models.CharField(max_length=50) 
    price           = models.IntegerField() 
    image           = models.ImageField(upload_to=settings.MEDIA_ROOT) 
    description     = models.TextField() 
    created_date    = models.DateTimeField(auto_now_add=True) 
 
    def __str__(self): 
        return self.title; 

设置.py

MEDIA_ROOT  = '/static/images/upload/' 
MEDIA_URL   = '/upload/' 

View .py

def home(request): 
    posts = Product.objects.filter(created_date__isnull=False) 
    return render(request, 'kerajinan/product_list.html', { 
        'posts'         : posts, 
        'categories'    : Category.objects.all(), 
    }) 

这是模板 product.html

<img src="{{post.image.url}}" alt="" /> 

你能帮我解决这个问题吗?

请您参考如下方法:

MEDIA_ROOT 是上传图片的绝对路径,因此您应该将设置更改为如下内容:

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/upload') 

第二个问题是图像域定义。 upload_to 参数是一个路径 relative到 MEDIA_ROOT/MEDIA_URL。

image = models.ImageField(upload_to='product') 

并且最好加入一些strftime()格式来减少单个目录中的文件数量:

image = models.ImageField(upload_to='product/%Y/%m/%d')