这是我以前的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/
project - 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/' % chapter .id)
我把它改成return HttpResponseRedirect('viewchapter/%i/' % chapter .id)
但是它们的结果都是一样的
当前路径viewbook/9/viewchapter/58/不匹配。
检测到两个问题:
- 相对URL,该URL可以在
redirect
呼叫 中使用领先的 redirect
函数不以django方式使用
/
来固定。Redirect可以接受硬编码的url,但是在这种情况下,应该传递带参数的视图名。正如Django文档所说,重定向可以接受视图或URL模式的名称和参数:
return redirect('some-view-name', foo='bar')
URL将通过反转在urls.py
中定义的URL模式来构建。在你的例子中,它将是
return redirect('viewchapter', chapt.id)
或
return redirect('viewchapter', id=chapt.id)