Django how the urls are resolved? -
im reviewing sample django code , trying understand how urls resolved?
list.html
categories
{% 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'), )
the above html list categories without problem , called when enter following in browser..[http:127.0.0.1:8000]
when hover on - href="{{p.get_absolute_url}} - url resolved to--[http://127.0.0.1:8000/category/electronics/]
the p.get_absolute_url resolved electronics im wondering how "category" resolved in 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 product page url created 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 meta tag") meta_description = models.charfield("meta description",max_length=255,help_text="content 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})
hope question clear...
get_absolute_url
function defined inside model (for example, category
) model this:
class category(models.model): name = models.charfield(max_length=200) ... def get_absolute_url(self): return "/category/%s/" % self.slug
it possible use reverse
function resolve url using pattern defined in urls.py
:
def get_absolute_url(self): return reverse('catalog_category', args=[str(self.slug)])
which equal old-fashioned form:
@models.permalink def get_absolute_url(self): return ('catalog_category', (), {'category_slug': str(self.slug)})
in both ways, calling get_absolute_url
method on category object, example category(name="electronics")
, result in string: /category/electronics/
.
as can see in urls.py
, second url pattern named catalog_category
, appeard in reverse function argument. when call reverse function, django urls.py files, looking pattern named catalog_category
, , final url generated replacing url parameter (category_slug) self.slug.
Comments
Post a Comment