zoukankan      html  css  js  c++  java
  • django 模板中url的处理

    在模板中直接添加‘/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/

  • 相关阅读:
    又过了一周
    本周学习情况
    5.12
    一周回顾
    npm修改全局包安装路径
    热力图之heatmap
    前端的发展历程
    idea打开maven项目没有别识别是maven项目
    nginx下部署vue项目
    WEB前端开发NodeJS
  • 原文地址:https://www.cnblogs.com/wswang/p/5523510.html
Copyright © 2011-2022 走看看