django 模板中url的处理
2016-05-24 21:13
330 查看
在模板中直接添加‘/home’这样的链接是十分不推荐的,因为这是一个相对的链接,在不同网页中打开可能会返回不一样的结果。
所以推荐的是
这种方式,或者
这里第二种方式同时需要在urls.py中设置,
同时对应的article_view应该有2个参数(request, pk)
get_absolute_url是一个方法,需要在model里声明一下;下面是官方的推荐使用方式
不推荐
更具体的可以参考一下 https://github.com/the5fire/django_selfblog/blob/master/selfblog/blog/models.py
这里作者使用了“伪静态url”,get_absolute_url方法如下:
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/
所以推荐的是
<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/
相关文章推荐
- go学习
- Google 2016 i/o 大会
- golang的SHA1withRSA的实现
- django 2
- Google Eventbus优缺点
- Golang游戏服务器
- ViewGroup setVisibility 为GONE 子View依然占用地方,其中的子EditText会出现点击焦点占用
- 【Algothrim】动态规划法实例1
- go语言模板引擎应用以及读取io流
- hdu5512Pagodas
- goldengate使用定义文件注意问题
- 【AC自动机+DP】USACO2012 JAN GOLD_Video Game Combos
- Term::Cap, Tgetend(), Tgoto, Tputs()
- golang设置每天12点定时任务
- Google推荐的图片加载库Glide介绍
- Uber如何使用Go打造了Uber QPS最高的服务
- Acionbar logo
- Acionbar logo
- 拾遗:Go 基础
- Django认证系统