无法在django上传图像使用MEDIA_ROOT和MEDIA_URL

时间:2015-04-23 04:41:50

标签: python django django-models

你好我想在admin django中制作上传图片,但是当我使用media_root和媒体网址图片无法上传时。这是model.py

$response->CompletedTrackDetails->TrackDetails->Events

setting.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;

view.py

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

这是tamplate product.html

def home(request):
    posts = Product.objects.filter(created_date__isnull=False)
    return render(request, 'kerajinan/product_list.html', {
        'posts'         : posts,
        'categories'    : Category.objects.all(),
    })
你可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:6)

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')