3

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?

rnevius
  • 26,578
  • 10
  • 58
  • 86
User0511
  • 665
  • 3
  • 11
  • 27

1 Answers1

13

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')
phoenix
  • 7,988
  • 6
  • 39
  • 45
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • thanks its work, but how to show image with tag img like this image cannot loaded. how? – User0511 Apr 23 '15 at 05:19
  • Here is the doc: https://docs.djangoproject.com/en/1.8/howto/static-files/#serving-files-uploaded-by-a-user-during-development – catavaran Apr 23 '15 at 05:22