Question

Currently working on a small Django e-commerce project and run into a small issue. For reference, I am using the Tango with Django book available online free.

I have an ImageField set in my models in order to specify an image for a product for the model of Product. I also have a model called Category which is referenced to the Product model using a ForeignKey.

The image uploads to the /static/products_img folder in the model, however, when the image is displayed in my template, the image links to /static/static/products_img folder. However, when I remove the /static in the model, and then upload an image through the admin interface, it uploads it to /products_img and not the static folder, in which of course it displays fine. But... it gets weirder, when I delete the newly created directory and place the image in the /product_img folder in the static folder, it still displays!

I'm so confused.

models.py

class Product(models.Model):
...
    image = models.ImageField(upload_to='static/products_img', blank=True)


template.html
<a href="{{ product.slug }}"><img src="{{ STATIC_URL }}{{ product.image }}" alt="{{ product.name }}" /></a>


settings.py
...
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
...
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    STATIC_PATH,
)
Was it helpful?

Solution

I think you have a confusion between static and media files. Static files are bundled with your apps (CSS, JS...), while media files are uploaded by users.

From what I understand, your products images are Media files, not Static files.

What if you replace your template part with:

<a href="{{ product.slug }}"><img src="{{ product.image.url }}" alt="{{ product.name }}" /></a>

and your model with :

image = models.ImageField(upload_to='products/img', blank=True)

And add the corresponding settings into your settings.py :

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
# with this, your media directory will be the same directory than your settings.py file
# you can also use a standard path like "/var/www/media"
# IMPORTANT : In any case, you have to create the directory by hand
MEDIA_ROOT = os.path.join(PROJECT_PATH, "media")
MEDIA_URL = "/media/"

If you upload an image into a product, it should now be saved under MEDIA_ROOT directory. The URL displayed in template should be /media/projects/img/image_name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top