我正在审核一个样本DJango代码并试图了解网址是如何解决的?
list.html
{% for c in active_categories %}
<a href="{{c.get_absolute_url}}">{{c.name}}</a><br />
{% endfor %}
urls.py
from django.conf.urls import *
urlpatterns = patterns('ecomstore.catalog.views',
(r'^$','index',{'template_name':'catalog/index.html'},'catalog_home'),
(r'^category/(?P<category_slug>[-\w]+)/$','show_category',{'template_name':'catalog/category.html'},'catalog_category'),
(r'^product/(?P<product_slug>[-\w]+)/$','show_product',{'template_name':'catalog/product.html'},'catalog_product'),
)
上面的html列出所有类别没有任何问题,当我在浏览器中输入以下内容时调用它.. [http:127.0.0.1:8000]
当我将鼠标悬停在 - href =“{{p.get_absolute_url}}时 - 我将网址解析为 - [http://127.0.0.1:8000/category/electronics/]
p.get_absolute_url仅解析为电子产品,但我想知道如何在网址中解析“类别”..
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50,unique=True,help_text='Unique value for product page URL created from name')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords",max_length=255,help_text="comma-delimited set of SEO Keywords for meta tag")
meta_description = models.CharField("Meta description",max_length=255,help_text="Content for description meta tag")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'categories'
ordering = ['-created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ('catalog_category',(),{'category_slug':self.slug})
希望我的问题很明确......
答案 0 :(得分:0)
get_absolute_url
是在模型中定义的函数(例如,Category
)模型,如下所示:
class Category(models.Model):
name = models.CharField(max_length=200)
...
def get_absolute_url(self):
return "/category/%s/" % self.slug
也可以使用reverse
函数来解析使用urls.py
中定义的模式的网址:
def get_absolute_url(self):
return reverse('catalog_category', args=[str(self.slug)])
几乎等同于一种老式的形式:
@models.permalink
def get_absolute_url(self):
return ('catalog_category', (), {'category_slug': str(self.slug)})
在两种方式中,在Category对象上调用get_absolute_url
方法(例如Category(name="electronics")
)将生成字符串:/category/electronics/
。
正如您在urls.py
中看到的那样,第二个url模式名为catalog_category
,它出现在reverse函数参数中。当您调用reverse函数时,Django将查看urls.py文件,查找名为catalog_category
的模式,并使用self.slug替换url参数(category_slug)生成最终的url。