[Answered ]-How to get image connected by Foreign Key via Template in django

0👍

There is so much wrong with your code, I suggest that you do the Django Tutorial first.

https://docs.djangoproject.com/en/1.8/intro/tutorial01/

But if you wan’t it working, here is how:

models.py

class Product(models.Model):
    category = models.ForeignKey(Category)
    name= models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique = True)
    price = models.IntegerField(default=100)

    def first_image(self):
        # code to determine which image to show. The First in this case.
        return self.images[0]

class ProductImage(models.Model):
    image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
    product = models.ForeignKey(Product, related_name='images')

views.py

def index(request):
    queryset = Products.objects.all()
    return render_to_response('site/index.html', {'products': queryset})

index.html

{% for product in products %} 
     <img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}

2👍

just try to understand the model that how i get the image url from models which related with foreignkey relationship.

my models:

class Product(models.Model):
    title           = models.CharField(max_length = 400)
    slug            = models.SlugField(max_length = 400,unique=True,null=True,blank=True)
    is_popular      = models.BooleanField(default=True)
    category        = models.ForeignKey(Category,on_delete=models.CASCADE)
    subcategory     = models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True,blank=True)
    childcategory   = models.ForeignKey(Childcategory,on_delete=models.CASCADE,null=True,blank=True)
    brand           = models.ForeignKey(Brand,on_delete=models.CASCADE,null=True,blank=True)
    description     = models.TextField()
    is_active       = models.IntegerField(choices=STATUS_CHOICES)
    created_date    = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = unique_slug_generator(self) 
        super(Product, self).save(*args, **kwargs)

    def show_image(self):
        return self.productmeaserment_set.first().first_image()

   
            
class ProductMeaserment(models.Model):
    product             = models.ForeignKey(Product,on_delete=models.CASCADE)
    measerment          = models.ForeignKey(Measerment,on_delete=models.CASCADE,null=True,blank=True)
    selling_price       = models.DecimalField(max_digits=20,decimal_places=2)
    offer_price         = models.DecimalField(max_digits=20,decimal_places=2)
    available_quantity  = models.IntegerField();
    is_active           = models.IntegerField(choices=STATUS_CHOICES)
    created_date        = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.measerment.name

    def first_image(self):
        return self.productmeasermentimage_set.first()
    


class ProductMeasermentImage(models.Model):
    productmeaserment   = models.ForeignKey(ProductMeaserment,on_delete=models.CASCADE)
    image               = models.FileField(upload_to='uploads/products')
    is_active           = models.IntegerField(choices=STATUS_CHOICES)
    created_date        = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.productmeaserment.product.title

views.py

from products.models import Product
def adminpanel(request):
    products=Product.objects.all()
    return render(request,'adminpanel/index.html',{'productsall':products})

templates/adminpanel/index.html

{% for item in productsall %}
            <tr>
                <div class="border1">
                  <td class="image-cell">
                    <img src="{{item.show_image.image.url}}">   #this is how i got image url.
                  </td>
                </div>
              <td data-label="title">{{item.title}}</td>
              <td data-label="category">{{item.category}}</td>
              <td data-label="subcategory">{{item.subcategory}}</td>
              <td data-label="brand">
                {{item.brand}}
              </td>
              <td data-label="description">
                {{item.description}}
              </td>
              <td class="created">
                  {{item.created_date}}
              </td>
            </tr>
            <tr>
            {% endfor %}
    

Leave a comment