无法在 Django 中使用 MEDIA_ROOT 和 MEDIA_URL 上传图片
Can't upload image in django use MEDIA_ROOT and MEDIA_URL
你好,我想在 admin django 中上传图片,但是当我使用 media_root 和媒体 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;
setting.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')
你好,我想在 admin django 中上传图片,但是当我使用 media_root 和媒体 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;
setting.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')