开发者

how to make tags?

开发者 https://www.devze.com 2023-01-06 01:11 出处:网络
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):

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):

  1. I want to have a separate class model for that, with a foreign key to a question
  2. In the form, I want the user to be able to add multiple tags, separated by a comma, and when the form is submitted, I want the tags to be stored in a table: each tag a registration

What should I use in the form, so tha开发者_如何学Got the tags separated by a comma to be saved in the database, each tag a registration? (for easy searching)

Thanks


django-taggit

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


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


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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消