2015-04-23 130 views
0

你好我想在管理员django上传图像,但是当我使用media_root和媒体url图像无法上传。这是model.py无法在django中使用MEDIA_ROOT和MEDIA_URL上传图像

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

,这是tamplate product.html

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

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

回答

3

MEDIA_ROOT绝对路径上传的图片,所以你应该将设置更改为这样的事情:

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

第二个问题是在图像字段定义。 upload_to参数是路径relativeMEDIA_ROOT/MEDIA_URL

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

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

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

感谢其工作,但如何显示像这样图像标签img的图像不能加载。怎么样? – User0511

+0

以下是文档:https://docs.djangoproject.com/en/1.8/howto/static-files/#serving-files-uploaded-by-a-user-during-development – catavaran