You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击HTML页面链接未跳转却追加URL致404,如何解决?

链接跳转异常导致404的解决方法

问题现象

点击HTML页面上的链接时,目标URL被追加到当前URL末尾,触发404错误,无法正常跳转。

问题根源

你的models.py中生成URL时缺少了HTTP协议的双斜杠//:

@property
def url(self):
    return f'http:127.0.0.1:8000/exames/acesso_medico/{self.token}'

浏览器会将http:127.0.0.1...识别为相对路径,而非完整的绝对URL,因此会把这段路径追加到当前页面的URL后,导致请求地址错误。

解决方案

方案1:修复URL格式,补充双斜杠

直接在生成URL时补上//,确保是完整的绝对路径:

@property
def url(self):
    return f'http://127.0.0.1:8000/exames/acesso_medico/{self.token}'

方案2:使用Django反向解析生成URL(推荐)

硬编码URL不利于维护,建议用Django的reverse函数反向解析URL,避免路径错误:

  1. 在models.py中导入reverse:
from django.urls import reverse

@property
def url(self):
    # 根据urls.py中定义的name反向生成路径
    return reverse('acesso_medico', kwargs={'token': self.token})
  1. 如果需要完整的绝对URL(包含域名和协议),可以在视图中结合request.build_absolute_uri生成,再传递给模板:
# 示例视图代码
def your_view(request):
    acessos_medicos = AcessoMedico.objects.all()
    for acesso in acessos_medicos:
        acesso.full_url = request.build_absolute_uri(acesso.url)
    return render(request, 'your_template.html', {'acesso_medicos': acessos_medicos})

模板中对应修改为:

<td><a href="{{ acesso.full_url }}">{{ acesso.full_url }}</a></td>

方案3:直接在模板中使用url标签

跳过model中的url属性,直接在模板里用Django的url标签生成链接,最规范:

{% for acesso in acessos_medicos %}       
<tr class="linha-tabela">
    <td>{{acesso.identificacao}}</td>
    <td>{{acesso.status}}</td>
    <td><a href="{% url 'acesso_medico' token=acesso.token %}">访问链接</a></td>
</tr>
{% endfor %}

内容的提问来源于stack exchange,提问作者LSD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:42:42