I am trying to make a website and part of that is having tags much like this site has. I am trying this:
def index(request):
storylist = Story.objects.order_by("id")
tagslist = []
for sto in storylist:
tagslist.append(sto.tags.split(","))
context = {"storylist": storylist,"tagslist":tagslist}
return render(request, "storyage/index.html", context)
But
-
It’s not working (I don’t know how to make the specific tags show up with the specific story).
-
Deleting a story breaks the whole thing.
You’re probably going to need to be more precise here.
-
If you are getting any error messages, please post the complete tracebacks.
-
When you say “It’s not working”, please specify what it is that you’re expecting to have happen, and what you’re getting as a result.
-
Please post the definition of the Story model
-
Please post the storyage/index.html template
Here you are storing the tags in comma-separated string inside your story model and trying to maintain a separate tagslist; but the issue with the is that storylist and tagslist will become coupled by position, in which case you delete a story the indices will no longer line up the way you would’ve expected when you don’t update tagslist and things will break.
A solution for this and particularly to make the tag management easier would be to create a separate Tag model and use ManyToManyField:
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Story(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
tags = models.ManyToManyField(Tag, related_name='stories')
created_at = models.DateTimeField(auto_now_add=True)
def index(request):
storylist = Story.objects.order_by("id").prefetch_related("tags")
context = {"storylist": storylist}
return render(request, "storyage/index.html", context)
And then your Django code would accordingly look something like this:
{% for story in storylist %}
<div class="story">
<h3>{{ story.title }}</h3>
<div class="tags">
{% for tag in story.tags.all %}
<span class="tag">{{ tag.name }}</span>
{% endfor %}
</div>
</div>
{% endfor %}
Reference Link: Code Review