简体   繁体   中英

Changing the way tags in django-taggit are input

I'm trying out django-taggit and really enjoying it. One thing that I can't figure out tho, is how to change the default comma-separated tag input into the django default many-to-many field with the filter_horizontal option (or even checkboxes). It would make more sense to what I want to do as I only want admins to be able to create tags, with content producers just choosing from the available ones
Found a similar question here
Using Check boxes in Taggit
But I can't make sense of what has to be plugged where to make it happen

Don't have the time to try to understand how taggit really works in order to to what I need, so I came up with a quick workaround - created a method inside the model that retrieves all available tags and displays them in the help text for the tags field.

tags = TaggableManager(blank=True, help_text = tag_helptext())    
def tag_helptext():
    help_text = "Options: "
    for t in Tag.objects.all():
        help_text += t.name + " ||| "
    return help_text

Then in the admin I removed priviledges to create new tags to everyone but the superuser.
Feels kinda hackish, but provides what I needed (to make it easy for users to use existing tags and avoid them creating new ones)

I came across the same problem, so I'm posting anyways to share my solution. Extract from the point 7.2 this document

To provide your own parser, write a function that takes a tag string and returns a list of tag names. For example, a simple function to split on comma and convert to lowercase:

def comma_splitter(tag_string):
return [t.strip().lower() for t in tag_string.split(',') if t.strip()]

You need to tell taggit to use this function instead of the default by adding a new setting, TAGGIT_TAGS_FROM_STRING and providing it with the dotted path to your function. Likewise, you can provide a function to convert a list of tags to a string representation and use the setting TAGGIT_STRING_FROM_TAGS to override the default value (which is taggit.utils._edit_string_for_tags ):

def comma_joiner(tags):
return ', '.join(t.name for t in tags)

If the functions above were defined in a module, appname.utils, then your project settings.py file should contain the following:

TAGGIT_TAGS_FROM_STRING = 'appname.utils.comma_splitter'
TAGGIT_STRING_FROM_TAGS = 'appname.utils.comma_joiner'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM