• 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/

  • 相关阅读:
    修改MySQL密码
    struts入门
    监听
    游戏外挂教程(转)
    “无法加载一个或多个请求的类型。有关更多信息,请检索 LoaderExceptions 属性 “之解决
    C# PropertyGrid控件应用心得
    登录时的"记住我"
    自动登录、记住我(保存登陆状态)实现
    UpdatePanel的使用方法
    asp.net中使用基于角色role的Forms验证
  • 原文地址:https://www.cnblogs.com/wswang/p/5523510.html
Copyright © 2020-2023  润新知