【问题标题】:Relative URL replace part of old url instead of add to old one in django相对 URL 替换旧 url 的一部分而不是添加到 django 中的旧 URL
【发布时间】:2018-02-20 15:29:16
【问题描述】:

我在 django 应用程序中的相对 url 有问题。

我的对象结构看起来像这样

Competitions/
    games/
    players/
    costs/

和指向它的网址

competitions/ - 所有比赛列表

{% for comp in competitions%}
    <li  onclick=window.location.href='{{comp.pk}}'>
        comp.name
    </li>
{% endfor %}

当我点击其中一个链接时,我被重定向到页面competitions/&lt;competitions_id&gt;

competitions/&lt;int:competition_id&gt; - 比赛的详细视图

competitions/games/&lt;int:competition_id&gt; - 挑选比赛中的所有游戏列表

{% for game in games%}
    <li  onclick=window.location.href='{{game.pk}}'>
        game.name
    </li>
{% endfor %}

所以当我在 url 上时:competitions/games/1 列出所有 id = 1 的比赛

<li onclick=window.location.href='1'> game1</li>
<li onclick=window.location.href='2'> game2</li>
<li onclick=window.location.href='3'> game3</li>
<li onclick=window.location.href='4'> game4</li>

例如,我在 game4 上单击我的 url 地址是 Competitions/games/4 而不是 Competitions/games/1/4 谁能解释一下原因。

【问题讨论】:

  • 两个提示:1/ 始终使用{% url %} 标签(或Python 代码中的reverse 函数) - 这样您就可以获得绝对网址(至少是绝对路径)并且您可以简单地更改您的 url 布局,而无需在整个地方修复代码 - 并且 2/ 当普通链接有效时不要使用 javascript(=> 用正确的链接替换所有 onclick=window.location.href 内容)。
  • 不是答案,但我建议您设计像/competitions/&lt;int:competition_id&gt;/games/ 这样的网址,以列出特定比赛中的所有游戏。
  • 然后具体游戏的详细视图看起来像/competitions/&lt;int:competition_id&gt;/games/&lt;int:game_id&gt;/
  • 我试过了,但问题是一样的。我有表格而不是列表项,因为这个表格我有 javascript

标签: python django python-3.x url


【解决方案1】:

问题是 url 不是以 / 结尾的

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2015-01-09
    • 1970-01-01
    • 2023-03-11
    • 2021-02-14
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多