Search code examples
djangoe-commerceadminprojectcommerce

Django Connecting Image with Product Name from Admin


Hey I hope someone will be able to help me out.

I'm working on a e-commerce website, I can add each product from the Admin db through django but I cant add the image, currently the code adds the same image to each product.

{% for Product in oldProducts %}
    <div class="col-lg-4">
      <img class="img-circle" src="{% static "ecommerce/img/weightgain2.png" %}" alt="Generic placeholder image" width="140" height="140">
      <h2>{{ Product.Name }}</h2>
      <p>{{ Product.Price }} </br> {{ Product.Description }}</p>
      <form method='POST' action="{% url 'ecommerce:addbasket' %}">
      {% csrf_token %}
      <input type="hidden" name="stuffNum" value="{{ Product.ProductID }}">
      <input type="hidden" name="stuffName" value="{{ Product.Name }}">
      <input type="hidden" name="stuffPri" value="{{ Product.Price }}">
      <input type="hidden" name="stuffDesc" value="{{ Product.Description }}">
      <button class="btn btn-default" type="submit">Add To Basket</button>
      </form>
    </div><!-- /.col-lg-4 -->
    {% endfor %}

How can I make each product to take a different image with the same name as the product?

class Product(models.Model):
ProductID = models.AutoField(db_column='ProductId', primary_key=True)  # Field name made lowercase.
Name = models.CharField(db_column='Name', max_length=255, blank=True, null=True)  # Field name made lowercase.
Price = models.TextField(db_column='Price', blank=True, null=True)  # Field name made lowercase. This field type is a guess.
Description = models.TextField(db_column='Description', blank=True, null=True)  # Field name made lowercase.
Image = models.TextField(db_column='Image', blank=True, null=True)  # Field name made lowercase.

Solution

  • You are using a Textfield instead of an ImageField which is why you can't choose an image to upload.

    Better change to this:

    class Product(models.Model):
        ProductID = models.AutoField(db_column='ProductId', primary_key=True)
        Name = models.CharField(db_column='Name', max_length=255, blank=True, null=True)
        Price = models.TextField(db_column='Price', blank=True, null=True)
        Description = models.TextField(db_column='Description', blank=True, null=True)
        Image = models.ImageField(upload_to='path/to/dir/for/images/', db_column='Image', blank=True, null=True)
    

    Then in your HTML write it like this:

    {% for Product in oldProducts %}
        <div class="col-lg-4">
            <img class="img-circle" src={{ Product.Image.url }} alt="Generic placeholder image" width="140" height="140">
            ...
       </div>
    {% endfor %}
    

    [PYTHON NOTES]: Please use product_id instead of ProductID etc. Use snake case convention. This is Python, not JS ;)

    Read more on the ImageField or search Google for more.