2017-01-19 83 views
0

這是我的模板文件:Django的 - 網址與變量(塞)

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

我試圖採取{{標籤}}作爲蛞蝓參數。可能嗎?接下來,我將嘗試創建一個頁面,在該頁面中我將列出在Sites模型的關鍵字字段中共存標籤的所有頁面。

我沒有標籤模式。我試圖把我的標記變量,並將其放入我的網址(標記/變量)。

我得到的標籤那樣: 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 
+0

你能告訴我們你的標籤模型? –

+0

我在上面稍微解釋了一下。對不起,我可憐的英語... – jundymek

回答

1

的標籤模型將會使你的生活更輕鬆
我假設你已經做出了正確的視圖標籤,使用slugify標籤到您的標籤轉換爲塞

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

,並在urls.py

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

偉大的解決方案。現在我的網址看起來應該:)是否有可能以簡單的方式恢復這個標籤?例如'現代化談話'回到'現代談話'? – jundymek

+0

嘗試使用[str.replace](https://docs.python.org/3/library/stdtypes.html#str.replace)'modern-talking'.replace(' - ','')=>'modern說話' –

+0

如果你的標籤包含 - 比你會有一些問題 –