无法在Django中上载图像使用媒体根和媒体URL

2024-04-28 23:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我想在管理员django上传图片,但当我使用媒体根和媒体url图片无法上传。这是model.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/'

视图.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(),
    })

这是tamplate product.html

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

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


Tags: pyimageurltitlemodels图片rootproduct
1条回答
网友
1楼 · 发布于 2024-04-28 23:46:31

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

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

第二个问题是图像场的定义。upload_to参数是指向MEDIA_ROOT/MEDIA_URL的路径relative

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

最好添加一些strftime()格式以减少单个目录中的文件数:

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

相关问题 更多 >