簡體   English   中英

無法使用MEDIA_ROOT和MEDIA_URL在Django中上傳圖片

[英]Can't upload image in django use MEDIA_ROOT and MEDIA_URL

您好,我想在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(),
    })

這是tamplate product.html

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

你能幫我解決這個問題嗎?

MEDIA_ROOT是上傳圖像的絕對路徑,因此您應該將設置更改為以下內容:

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

第二個問題是圖像字段定義。 upload_to參數是對於MEDIA_ROOT / MEDIA_URL的路徑。

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

最好添加一些strftime()格式以減少單個目錄中的文件數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM