Reputation: 5208
if I have a question and answer system, and I want to add a tag feature, as for every question I should have some tags, separated by a comma (just like Stackoverflow):
What should I use in the form, so that the tags separated by a comma to be saved in the database, each tag a registration? (for easy searching)
Thanks
Upvotes: 1
Views: 310
Reputation: 373
as per 2020, this is working, simple django solution: models.py:
from django.db import models
from django.contrib.auth.models import User
class ExamplePost(models.Model):
Title = models.CharField(max_length=100)
Tags = models.ManyToManyField('Need', related_name='plants')
entry_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.species}'
class ExampleTag(models.Model):
Name = models.CharField(max_length=100)
Link = models.URLField(max_length=1000, null=True, blank=True, default="None")
def __str__(self):
return f'{self.title}'
In example.html:
<div class="card-body">
<h2 class="card-title">{{ ExamplePost.title }}</h2>
<h5> Tags : </h5>
<ul class="list-group list-group-horizontal-sm">
{% for Tag in ExamplePost.tags.all %}
<p class="p-2 bg-light text-warning">
<h3><span class="badge badge-pill badge-warning">{{ ExampleTag.name }} </span></h3>
</p>
{% endfor %}
</ul>
</div>
Upvotes: 0
Reputation: 10603
update: read the docs to see how the tag input string results in tags, http://github.com/alex/django-taggit/blob/master/docs/forms.txt
Upvotes: 7
Reputation: 699
Yeah.. contenttypes framework is the best way to create tags.
class TagName(models.Model):
name = models.CharField(max_length=255)
class Meta:
pass
class Tag(Model):
tag = models.ForeignKey(TagName, related_name="tag_objects")
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(ugettext('object id'), blank=True, null=True)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
pass
Upvotes: 0
Reputation: 1355
I agree that you'd better use reusable tagging app, but if you're not afraid to get your hands dirty, check out Django contenttypes framework
Upvotes: 3