K
K
kuskov2019-05-08 08:55:16
Django
kuskov, 2019-05-08 08:55:16

Django 2, ForeignKey of bound model to template?

Good time of the day!
Dear django pros, I'm learning Django 2 The
question is not difficult, but as a beginner, I come across it for the first time and I can't understand.
There are two models:

class Post(models.Model):
  slug = models.SlugField(max_length=150, blank=True, unique=True)
        .......
  title = models.CharField(max_length=150, db_index=True, verbose_name='Заголовок')

  def get_images(self):
    return self.images.all

class Picture(models.Model):
  picture = models.ImageField(null=True, blank=True, upload_to=gen_filename)
  post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='images')

And view:
def object_detail(request, slug):
  post = Post.objects.get(slug__iexact=slug)
  gallery = Picture.objects.all()
  return render(request, 'object/object_detail.html', context={
    'post': post,
    'gallery': gallery})

I don’t understand how to describe in the template so that only the images associated with it are displayed for each Post.
I can't find a solution on the Internet, nothing works. I just came up with this:
{% for picture in gallery %}
  <a class="col-6 mygal" data-fancybox="gallery" href="{{ picture.picture.url }}">
    <img alt="{{ picture.picture.title }}" src="{{ picture.picture.url }}">
  </a>					
{% endfor %}

But in this case, images of all posts are displayed under each post.
Save and thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Maltsev, 2019-05-08
@hellpirat

Go through the tutorial on the official Django website and you will understand :)
Well, this section after https://docs.djangoproject.com/en/2.2/topics/db/
And the answer to your question:
gallery = Picture.objects.filter(post=post)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question