您的位置:首页 > 编程语言 > Go语言

django 模板中url的处理

2016-05-24 21:13 330 查看
在模板中直接添加‘/home’这样的链接是十分不推荐的,因为这是一个相对的链接,在不同网页中打开可能会返回不一样的结果。

所以推荐的是

<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>


这种方式,或者

<a href={% url 'article' article.pk %} >


这里第二种方式同时需要在urls.py中设置,

url(r'^article/(?P<pk>[0-9]+)/$', article, name='article'),


同时对应的article_view应该有2个参数(request, pk)

  

get_absolute_url是一个方法,需要在model里声明一下;下面是官方的推荐使用方式

不推荐

# 不推荐
def get_absolute_url(self):
return "/people/%i/" % self.id
# 推荐

def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('people.views.details', args=[str(self.id)])

# 不推荐

def get_absolute_url(self):
return '/%s/' % self.name

<!-- BAD template code. Avoid! -->
<a href="/people/{{ object.id }}/">{{ object.name }}</a>

# 推荐


<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>


  

更具体的可以参考一下 https://github.com/the5fire/django_selfblog/blob/master/selfblog/blog/models.py
这里作者使用了“伪静态url”,get_absolute_url方法如下:

def get_absolute_url(self):
return '%s/%s.html' % (settings.DOMAIN, self.alias)


alias是自己设置的,生成的链接就是: http://example.com/alias这种,由于一篇文章的链接是固定的,所以看上去像静态页面一样  
  

参考链接:
https://github.com/the5fire/django_selfblog http://huacnlee.com/blog/django-url-routes-and-get-absolute-url/ https://docs.djangoproject.com/en/1.9/ref/models/instances/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: