简体   繁体   English

Django-带变量的URL(段)

[英]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 urls.py

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

I am trying to take {{ tag }} as slug parameter. 我正在尝试将{{tag}}作为参数。 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. 接下来,我将尝试创建一个页面,在该页面中,我将在“站点”模型的“关键字”字段中列出所有包含cointain标签的页面。

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 我以这种方式获取标签:index.view

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

calculations.py 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 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 我假设您已经制作了正确的视图标签,请使用slugify标签将您的标签转换为slug

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

and in the urls.py 并在urls.py中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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