Thursday, April 9, 2015

Django taxonomy category

# pip install django-taggit

# python manage.py schemamigration taggit --auto

# python manage.py migrate taggit

If you are using South you’ll have to add the following setting, since taggit uses Django migrations by default:

SOUTH_MIGRATION_MODULES = {
    'taggit': 'taggit.south_migrations',
}

And then to any model you want tagging on do the following:

models.py:

from django.db import models

from taggit.managers import TaggableManager

class News(models.Model):
    # ... fields here

    tags = TaggableManager()

If, when saving a form, you use the commit=False option you’ll need to call save_m2m() on the form after you save the object, just as you would for a form with normal many to many fields on it:

if request.method == "POST":
    form = MyFormClass(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        obj.save()
        # Without this next line the tags won't be saved.
        form.save_m2m()

forms:

from taggit.forms import TagField, TagWidget

class NewsForm(ModelForm):
    tags = TagField(label=_('Tags'), widget=TagWidget(attrs={'size': 80}), help_text='A comma-separated list of tags')
    title = forms.CharField(label=_('Title'), widget=forms.TextInput(attrs={'size': 80}))
    class Meta:
        model = News
        fields = ['tags', 'title']
        #widgets = {
        #    'tags': TagWidget(),
        #}

views.py:

def ls_news(request):
    news_list = News.objects.order_by('-update_date')
    return render(request, 'administrator/news/index.html', locals())

template/administrator/news/index.html:

{% for n in news_list %}
    <!-- method 1 -->
    {{ n.tags.all|join:", " }}

    <!-- method 2 -->
    {% for t in n.tags.all %}
       {{ t.name }}
    {% endfor %}
{% endfor %}

To show all available tags:

from taggit.models import Tag

def add_news(request):
    tagsall = Tag.objects.all()
    return render(request, 'administrator/news/add.html', locals())
add_news = login_required(add_news)

{{ tagsall|join:', ' }}

Reference:

https://github.com/alex/django-taggit
https://github.com/fizista/django-taggit-templatetags2

https://django-taggit.readthedocs.org/en/latest/getting_started.html
http://stackoverflow.com/questions/16091940/django-taggit-in-edit-form
http://stackoverflow.com/questions/5359714/django-django-taggit-form
http://stackoverflow.com/questions/5742856/django-tagging-or-django-taggit-or-something-else
http://stackoverflow.com/questions/12894154/get-all-tags-from-taggit

No comments: