A
A
Alex2019-06-19 05:09:47
Django
Alex, 2019-06-19 05:09:47

How to attach a tag to a post in django?

I didn't really understand how to add a tag to a post...
MODELS.PY

class Post(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=32)
    image = models.URLField()
    content = models.TextField()
    tag = models.ManyToManyField('Tag', blank=True, related_name='posts')

    def __str__(self):
        return self.title

class Tag(models.Model):
    title = models.CharField(max_length=32)

    def __str__(self):
        return self.title

In the admin panel, if you select the created tag through the shell, then in the template it is displayed as main.Tag.None. (main - application name) How to fix this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2019-06-19
@SenderD

In the admin panel, if you select the created tag through the shell, then in the template it is displayed as main.Tag.None. (main - application name) How to fix this?

Everything comes out right.
Post is a list of posts, you only output one. You have a list of tags attached to the post (not ForeignKey), so you have a list and output that you must process.
In the template, add .all and you will see a list of tags associated with this post. Well, then process it like a list
Z.Y. In a field model with a ManyToManyField, it is better to set the variable name in the plural, that is, tags, not tag.

S
Sergey Gornostaev, 2019-06-19
@sergey-gornostaev

Django: Many-to-many relationships

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question