A
A
Andrey Voskresensky2016-03-12 20:57:16
Django
Andrey Voskresensky, 2016-03-12 20:57:16

How to display articles by tags in django?

Actually I have 2 classes: "Main" and "tags". The "Main" class has an FK on "tags". How to display a list of articles from "Main" is not a problem! also displaying all tags from "tags" is also not a problem (meaning as a list)! But here's how to make sure that all tags are links to articles from Maine with these tags??

class Main(models.Model):
  link_name = models.CharField(max_length = 25)
  topic_name = models.CharField(max_length = 100)
  content = models.TextField()
  tag_in_main = models.ForeignKey(Tag)
  def __str__ (self):
    return self.link_name
    	
  class Meta:
    ordering = ["-id"]

class Tag(models.Model):
  tag_main = models.CharField(max_length = 25, default=1)
  def __str__ (self):
    return self.tag_main

вьюшка
def tag(request):
  tag = Main.objects.all()
  content={
    "tag":tag
  }
  return render (request, "index_tag.html", content )

хтмл
{% for obj in tag %}
  <a href='{%url 'tag' id=obj.tag_main.id %}'>{{obj.tag_in_main}}</a><p>
      
{% endfor %}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
Oscar Django, 2016-03-12
@Voskresenskyi

class Main(models.Model):
  link_name = models.CharField(max_length = 25)
  topic_name = models.CharField(max_length = 100)
  content = models.TextField()
  def __str__ (self):
    return self.link_name
    	
  class Meta:
    ordering = ["-id"]

class Tag(models.Model):
  name = models.CharField(max_length = 25, default=1)
  main = models.ManyToManyField(Main, related_name='tags')
  def __str__ (self):
    return self.name

def main_tag(request, tag_id):
  main = Main.objects.filter(tags__id=tag_id)
  content={
    "main": main
  }
  return render (request, "index_tag.html", content )

...
url(r'^main/(\d+)/$', main_tag, name='main_tag'),
...

{% for m in main %}
  Name: {{ m.topic_name }}
  Text: {{ m.content }}
  Tags:
  {% for tag in m.tags %}
    <a href="{% url "main_tag" tag.id %}">{{ tag.name }}</a>
  {% endfor %}
{% endfor %}

C
Cyber_bober, 2016-03-12
@Cyber_bober

def postInTags(request, id):
  tags = Tag.objects.filter().get(id=id)
  posts = tags.post_set.all()
  return render(request, 'tag_posts.html', {'posts': posts, 'tags': tags})

A
Armenian Radio, 2015-01-03
@gbg

Start by clearing the cache using standard tools.

A
Artix, 2015-01-03
@nikkorejz

I suggest creating a backup of important data on the computer, and then doing a hard reset (hard reset)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question