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])
验证步骤
- 重启Django开发服务器;
- 访问合并页面
games,点击每个游戏链接,检查是否能正确跳转到对应详情页; - 若仍出现404,查看浏览器控制台的请求URL,对比URL配置路径是否一致,同时检查对应模型中是否存在该slug的对象。
内容的提问来源于stack exchange,提问作者Byansi
相关产品推荐
相关产品推荐

