Issue
I am trying to create a relationship where a blog post can be assigned any number of tags, and a tag can be associated with any number of blog posts. I'd like to be able to use the Django admin interface to assign tags to posts, and to assign posts to tags.
Right now, to create a blog post and assign any number of tags, here is my model for the posts:
class Post(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=100, unique=True, null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
updated_on = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField("Tags", blank=True)
content = RichTextUploadingField()
created_on = models.DateTimeField(auto_now_add=True)
And the model defining the tags:
class Tag(models.Model):
name = models.CharField(max_length=20, unique=True)
This works. I can log into the admin interface and create a bunch of tag objects, then create a post object and assign it any number of those tags.
But let's say I also want to do the opposite. I want to be able to log into the admin interface, select a tag object, and then associate it with any number of post objects.
I tried to do this by defining a ManyToManyField
in the Tag
model like so:
class Tag(models.Model):
name = models.CharField(max_length=20, unique=True)
posts = models.ManyToManyField("Post", blank=True, related_name="posts")
This does show a list of posts on the change tag page, but I really only want it to show the tags that are associated with that post. And using the admin interface, I'd like to have the ability to select other tags to assign to that post. So I then tried to use a ForeignKey
, but that will only allow me to select one post.
I know how I can override the default admin ModelAdmin.change_form_template
with a separate query to display the tags assigned to the posts. But I wasn't sure if there was a way to do this without overriding the default template.
Edit: I've revised this question to clarify what I'm trying to achieve. I now believe my model is set up correctly. But I was (likely incorrectly) thinking I could add the other field to the second model to make it appear in the admin interface.
Solution
I was making this much harder than it needed to be. In order to use the admin interface to assign tags to posts using the models in my question, I just needed to create an Inline
class:
class TagInline(admin.StackedInline):
model = Tag.post.through
And then specify it in inlines
under PostAdmin
:
inlines = [TagInline]
Now, the relationships appear in the Posts objects in the admin interface.
Thank you to @YongjinJo for getting me on the right track!
Answered By - JoshG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.