2015-04-23 129 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