简体   繁体   中英

Django - url with variable (slug)

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

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'),

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