0

I’ve two models which display in the same panel in admin using TabularInline

models.py

class Multimg(models.Model):
    post = models.ForeignKey('Post', null=True, blank=True, on_delete=models.CASCADE)
    caption = models.TextField(max_length=50, null="true", blank=True)
    text = tinymce_models.HTMLField(null="true")
    multimg = models.ImageField(upload_to="images", verbose_name='Image', null="true", blank=True,)
   
class Post(models.Model):
    title = models.CharField(max_length=50)
    highlight = models.TextField(max_length=250, null="true", blank=True,)
    image_article = models.ImageField(upload_to="images", verbose_name='Image', null="true")
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

admin.py

class MultiAdmin(admin.TabularInline):
    model = Multimg
    extra = 3

@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    model = Post
    inlines = [ MultiAdmin ]

I want to display the objects of these two models in the same details template and filter their objects to display based on the Post.id I’m using get_context_data to display the element of the Multimg Model

the Post model is causing no problems But when I try to display the Multimg object I cannot display the objects related only to the post details

views.py

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.object.id})

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['posts'] = Post.objects.all()
        context['multimgs'] = Multimg.objects.all()
        return context

post_detail.html

      <h1>{{ post.title }}</h1>

      <p> {{ post.author }}</p>
      <p> {{ post.date_posted|date:"M d, Y" }} </p>

      {% if post.image_article %}
      <img src="{{ post.image_article.url }}">
      {% endif %}

      {% for multimg in posts %}
      <p> {{ multimg.caption }}</p>
      <p> {{multimg.text|safe }}</p>

      {% if multimg.multimg %}
      <img src="{{ multimg.multimg.url }}">
      {% endif %}
      {% endfor %}

I’m able to display all its object using the tag {% for multimg in multimgs %} but when I try to display only the objects related to that particular post detail using {% for multimg in posts %} I display nothing.

I’m assuming the context is not able to make a relationship between that particular detail post and the object of this model but I’m confused about the approach I should use in order to achieve that. Can someone help with this?

1 Answers1

0

I found a solution in this answer

Using {% for multimg in object.multimg_set.all %}

Solved the problem