2
votes

hello i want to make upload image in admin django but when i use media_root and media url image can not upload. this is 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(),
    })

and this is tamplate product.html

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

can you help me solve this problem?

1

1 Answers

12
votes

MEDIA_ROOT is an absolute path to the uploaded images so you should change the setting to something like this:

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

The second problem is in the image field definition. upload_to argument is a path relative to the MEDIA_ROOT/MEDIA_URL.

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

And it is better to add some strftime() formatting to reduce the number of files in the single directory:

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