Django重定向URL拼接问题:URL重复拼接致路径不匹配求助
问题详情
- 当前URL:
http://127.0.0.1:8000/viewbook/8/viewchapter/57/ - 期望重定向URL:
http://127.0.0.1:8000/viewbook/8/viewchapter/57/ - 实际重定向URL:
http://127.0.0.1:8000/viewbook/8/viewchapter/57/ - 报错信息:
The current path, viewbook/9/viewchapter/58/, didn’t match any of these.
项目urls.py代码
from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ]
home.urls.py代码
from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('',views.home,name='home'), path('viewbook/<int:id>/', views.viewbook , name='viewbook'), path('viewchapter/<int:id>/', views.viewchapter , name='viewchapter'), path('viewpost/<int:id>/', views.viewpost , name='viewpost'), ]
views.py相关代码
def viewbook(response , id): book = Book.objects.get(id = id) allchapters = Chapter.objects.all() chapters = [] for chapt in allchapters: if chapt.Book.id == book.id: chapters.append(chapt) inputform = ChapterForm() if response.method == 'POST': form = ChapterForm(response.POST) if form.is_valid(): chapt = Chapter(Book = book , chapterNum = response.POST['chapterNum'] , chapterText = "") print(chapt) chapt.save() print(Chapter.objects.get(id= chapt.id)) return redirect('viewchapter/%i/' %chapt.id) inputform.fields["chapterNum"].initial =len(chapters) + 1 context = { 'book' : book, 'form' : inputform, 'chapters' : chapters } return render(response , 'viewbook.html' , context) def viewchapter(response , id): chapter = Chapter.objects.get(id = id) context = {'chapter' : chapter} return render(response , 'viewchapter.html', context)
用户排查:我认为问题出在这一行return redirect('viewchapter/%i/' %chapt.id),改为return HttpResponseRedirect('viewchapter/%i/' %chapt.id)后,仍出现相同的路径不匹配错误。
解决方案
问题出在相对路径重定向和未使用Django URL反向解析机制:
错误原因
当你在viewbook/8/路径下执行redirect('viewchapter/%i/' %chapt.id)时,Django会将其解析为当前路径的相对路径,最终生成viewbook/8/viewchapter/58/,但你的URL配置中只存在根路径下的viewchapter/<int:id>/,因此触发路径不匹配报错。HttpResponseRedirect同样处理相对路径,所以换用它也无法解决问题。正确修复方式
使用Django的命名URL反向解析,生成正确的绝对路径:- 方式一:直接调用命名URL(带命名空间)
return redirect('home:viewchapter', chapt.id) - 方式二:使用
reverse函数from django.urls import reverse return redirect(reverse('home:viewchapter', args=[chapt.id]))
- 方式一:直接调用命名URL(带命名空间)
补充说明
你的URL配置中viewchapter是直接挂载在根路径下的,正确访问路径应为http://127.0.0.1:8000/viewchapter/58/,反向解析会自动生成该正确路径。
内容的提问来源于stack exchange,提问作者shehan Maleesha Peiris
相关产品推荐
相关产品推荐

