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

Django合并QuerySet后get_absolute_url跳转404错误求助

Django get_absolute_url 404 错误修复方案

核心错误点排查

从提供的代码中,可定位出三个直接导致404的问题:

1. Adventure模型URL名称不匹配

Adventure模型的get_absolute_url调用了reverse('adves', ...),但Adventure的URL配置中,对应视图的名称是adv,名称不匹配导致生成的URL无效。

2. Racing模型双重错误

  • get_absolute_url错误指向Action的URL名称act,而非Racing自身的URL名称rac;
  • Racing视图中错误地从Action模型查询对象,实际应从Racing模型查询。

3. 潜在URL命名空间冲突(可选优化)

若多个app存在相同路径配置,未添加命名空间可能引发冲突,不过当前问题核心是名称不匹配。


修复代码

1. 修正Adventure模型的get_absolute_url

# adventure/models.py
class Adventure(models.Model): 
    # ... 其他字段
    def get_absolute_url(self):
        # 将'adves'改为URL配置中对应的name='adv'
        return reverse('adv', args=[self.slug])

2. 修正Racing模型的get_absolute_url

# racing/models.py
class Racing(models.Model): 
    # ... 其他字段
    def get_absolute_url(self):
        # 将'act'改为Racing自身的URL名称'rac'
        return reverse('rac', args=[self.slug])

3. 修正Racing视图的查询模型

# Racing/views.py
from django.shortcuts import render, get_object_or_404
from .models import Racing  # 确保导入Racing模型

def rac(request, description):
    # 将Action改为Racing,匹配当前模型
    description = get_object_or_404(Racing, slug=description)
    context = {'description': description}  # 变量名小写符合PEP8规范
    return render(request, 'description.html', context)

4. 可选:为各app添加URL命名空间(避免后续冲突)

若项目后续扩展,建议给每个app的URL添加命名空间,避免名称冲突:

在项目根URL配置中:

# project/urls.py
path('action/', include(('action.urls', 'action'), namespace='action')),
path('adventure/', include(('adventure.urls', 'adventure'), namespace='adventure')),
path('racing/', include(('racing.urls', 'racing'), namespace='racing')),
path('puzzle/', include(('puzzle.urls', 'puzzle'), namespace='puzzle')),

对应模型的get_absolute_url改为带命名空间的形式:

# Action/models.py
def get_absolute_url(self):
    return reverse('action:act', args=[self.slug])

# Adventure/models.py
def get_absolute_url(self):
    return reverse('adventure:adv', args=[self.slug])

# Racing/models.py
def get_absolute_url(self):
    return reverse('racing:rac', args=[self.slug])

# Puzzle/models.py
def get_absolute_url(self):
    return reverse('puzzle:puz', args=[self.slug])

验证步骤

  1. 重启Django开发服务器;
  2. 访问合并页面games,点击每个游戏链接,检查是否能正确跳转到对应详情页;
  3. 若仍出现404,查看浏览器控制台的请求URL,对比URL配置路径是否一致,同时检查对应模型中是否存在该slug的对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:22:59