Christopher Reid
Christopher Reid

Reputation: 4484

Constraining foreign key to a specific instance of a model

I have two instances of a model 'Product'. In the admin I upload two images to each one. When the images are called on their respective pages instead of the two, all four images are served to each page. How can I restrict the images to their proper products without them spilling into the wrong ones?

I have this relationship in my models.py

class Product(models.Model):
    product_name = models.CharField(max_length=200) 
    def __unicode__(self):
        return self.product_name

class Image(models.Model):
    product_image = models.ForeignKey(Product)
    image = models.ImageField(upload_to='image')
    image_id = models.CharField(max_length=200)

views.py

def productpage(request, product_image_id):
    product_list = Product.objects.all()
    image_list = Image.objects.all()
    product = get_object_or_404(Product, pk=product_image_id)
    image = get_object_or_404(Image, pk=product_image_id)
    return render(request, 'polls/productpage.html', {
        'product': product, 'image': image, 
        'product_list' : product_list, 'image_list':image_list

TEMPLATE

     {% for image in image_list %}      
<div id ="{{ image.image_id }}"class="numbers"><img src="{{ image.image.url }}" alt="slide"></div>
     {% endfor %}
     }

I'm getting this result on both product pages, which returns all 4 images, when there should only be 2.

<div id ="one"class="numbers"><img src="/media/image/red1.jpg" alt="slide"></div>

<div id ="two"class="numbers"><img src="/media/image/red2.png" alt="slide"></div>

<div id ="one"class="numbers"><img src="/media/image/blue1.jpg" alt="slide"></div>

<div id ="two"class="numbers"><img src="/media/image/blue2.png" alt="slide"></div>

Upvotes: 0

Views: 24

Answers (1)

Rohan
Rohan

Reputation: 53336

Instead of getting image_list which is all images, you can use product and get images only for that. You can do that in template itself using product.image_set.all() as

{% for image in product.image_set.all %}      
<div id ="{{ image.image_id }}"class="numbers"><img src="{{ image.image.url }}" alt="slide"></div>
{% endfor %}

Upvotes: 2

Related Questions