D
D
dstdfx2016-02-25 23:42:00
Django
dstdfx, 2016-02-25 23:42:00

How to implement tag search using django-taggit?

Casting guru jangi, what am I doing wrong? I get 404
models.py :

from taggit.managers import TaggableManager
class Article(models.Model):
    title = models.CharField(max_length=50)
    pub_date = models.DateTimeField('date published')
    text = models.TextField()
    tags = TaggableManager()

views.py:
def index(request):
    lastet_articles_list = Article.objects.order_by('-pub_date')
    all_tags = []
    for article in lastet_articles_list:
        all_tags += article.tags.names()
    all_tags = list(set(all_tags))
    context = {
        'lastet_articles_list': lastet_articles_list,
        'all_tags': all_tags,
    }
    return render(request, 'article/index.html', context)


def article(request, article_id):
    article = get_object_or_404(Article, id=article_id)
    return render(request, 'article/article.html', {'article': article})

def search_by_tag(request, tag):
    articles_with_tag = Article.objects.filter(tags__name__in=[tag])
    return render(request, 'article/tags.html', {'articles_with_tag': articles_with_tag})

URLs.py:
...
url(r'^tag/(<tag>[a-zA-Z])+/$', views.search_by_tag, name='search'),

index.html:
...
            {% if all_tags %}
                {% for tag in all_tags %}
                    <li><a href="tags/{{ tag }}">{{ tag }}</a></li>
                {% endfor %}
            {% endif %}
...

tags.html:
{% if articles_with_tag %}
            {% for article in articles_with_tag %}
                <div class="post-preview">
                    <a href="/article/{{ article.id }}/">{{ article.title }}</a><br>
                    {% for article_tag in article.tags.names %}
                        <span class="tags"><i class="fa fa-tag fa-lg"></i>{{ article_tag }}</span>
                    {% endfor %}
                    <p class="post-meta">Posted {{ article.pub_date }}</p>
                </div>
                <hr>
            {% endfor %}
        {% endif %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2016-02-26
@dstdfx

url(r'^tag/(?P<tag>[a-zA-Z]+)/$', views.search_by_tag, name='search'),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question