2

I would like to return in my Link.html the number of links contained in allLinks JSON variable. So far I guess I misunderstand the use of get_context_data() and how to pass in context['CountLink'] the total count of links for each Post.

With the current code, I got:

Liste des recherches

terre : <QuerySet [<Post: terre>, <Post: océan>]> Links
océan : <QuerySet [<Post: terre>, <Post: océan>]> Links

models.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    url = models.URLField(max_length=255)
    allLinks = models.JSONField()

    def __str__(self):
        return self.title

views.py

class LinkView(ListView):
    model = Post
    template_name = 'link.html' 

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

Link.html

  {% for post in object_list %}
  <li>
    <a href="{% url 'DetailLink' post.pk %}">{{ post.title }}</a> :
    {{CountLink}} Links
  </li>
  {% endfor %}

Example of allLinks: {"0": "github.com/kubernetes/kubernetes/releases/tag/v1.26.0", "1": "kubernetes.io/docs/concepts/overview/what-is-kubernetes",}

aaron
  • 39,695
  • 6
  • 46
  • 102
fransua
  • 501
  • 2
  • 18
  • 2
    Please *don't* use JSON blobs... Use a `ManyTOManyField`... – Willem Van Onsem Dec 18 '22 at 12:52
  • exemple of allLinks : {"0": "https://github.com/kubernetes/kubernetes/releases/tag/v1.26.0", "1": "https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/",} – fransua Dec 19 '22 at 14:57

2 Answers2

1

Use the built-in length template filter:

{{ post.allLinks|length }} Links
aaron
  • 39,695
  • 6
  • 46
  • 102
0

You can use count() In your case I think you want something like that, it will return count of Post model objects

context['CountLink'] = Post.objects.all().count()

For more info check this

Alasgar
  • 134
  • 9