Home > Software design >  ValueError at /category/ The 'image' attribute has no file associated with it
ValueError at /category/ The 'image' attribute has no file associated with it

Time:12-22

I am building an Ecommerce website in Django for the first time. Some how despite following the YT tutorial, I am not able to render image that are uploaded from my Django Admin Panel. Here are my codes:

  1. Models.py
class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField()
    image = models.ImageField(null=True, blank=True, upload_to='image/')

    def __str__(self):
        return self.name
  1. Views.py
def category(request):
    products = Product.objects.all()
    context = {"products":products}
    return render(request,'store/category.html', context)
  1. category.html
{% for product in products %}

<div >
    <div >
        <div  data-setbg="{{product.image.url}}">
            <div >New</div>
            <ul >
                <li><a href="{{product.imageURL}}" ><span ></span></a></li>
                <li><a href="#"><span ></span></a></li>
                <li><a href="#"><span ></span></a></li>
            </ul>
        </div>
        <div >
            <h6><a href="#">{{product.name}}</a></h6>
            <div >
                <i ></i>
                <i ></i>
                <i ></i>
                <i ></i>
                <i ></i>
            </div>
            <div >${{product.price|floatformat:2}}</div>
        </div>
    </div>
</div>
{% endfor %}
  1. settings.py
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Error I get: error screenshot

Please Help. Thank you.

I tried to render images in django by following along a Youtube Tutorial.

CodePudding user response:

Django shows an error when the file is not associated with the image field. While saving the object of Product model, make sure to add an image file to the field. You can use the following snippet :

<div  data-setbg="{% if product.image %}{{product.image.url}}{% endif %}">
  • Related