0

This is my template file:

{% for tag, count in tags.items %}
     <a href="{% url 'tags'  slug=tag.slug  %}">{{ tag }}</a> ({{count}}),
{% endfor %}

urls.py

url(r'^tag/(?P<slug>[\w-]+)/$', views.tags, name='tags'),

I am trying to take {{ tag }} as slug parameter. Is it possible? Next I would try to create page where I will list all pages that cointain tag in keywords field in Sites model.

I don't have tag model by the way. I am trying to take my tag variable and put it into my url (tag/tagvariable).

I get tags that way: index.view

tags = Tags().all_tags()
context['tags'] = tags

calculations.py

class Tags():

    def all_tags(self):
        sites = Site.objects.values('keywords')
        keywords = []
        tags = []
        for site in sites:
            keywords.append(site['keywords'].split(','))
        for keyword in keywords:
            for tag in keyword:
                tags.append(tag.strip())
        return(dict(Counter(tags)))

models.py

class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'Subcategory',
        chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True)
    name = models.CharField(max_length=70)
    description = models.TextField()
    keywords = MyTextField()
    date = models.DateTimeField(default=datetime.now, editable=False)
    url = models.URLField()
    is_active = models.BooleanField(default=False)

    def get_absolute_url(self):
        return "%s/%i" % (self.subcategory.slug, self.id)

    class Meta:
        verbose_name_plural = "Strony"

    def __str__(self):
        return self.name
2
  • can you show us your tag model ? Commented Jan 19, 2017 at 23:39
  • I explained it a little bit above. Excuse me for my poor english... Commented Jan 19, 2017 at 23:47

1 Answer 1

2

A tag model is going to make your life easier
I'm assuming that you've make the correct view tag, use the slugify tag to convert your tag to a slug

{% for tag, count in tags.items %}
     <a href="{% url "tags"  tag|slugify  %}">{{ tag }}</a> ({{count}}),
{% endfor %}

and in the urls.py

url(r'^tag/(?P<slug>[-\w]+)/$', views.tags, name='tags'),
Sign up to request clarification or add additional context in comments.

3 Comments

Great solution. Now my url looks like it should:) Is it possible to revert this tag in simply way? For example 'modern-talking' back to 'modern talking'?
try with str.replace 'modern-talking'.replace('-', '') => 'modern talking'
if your tag contain - than your going to have some problems

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.