Search code examples
djangodjango-urlsdjango-url-reverse

django redirect url concatenating to the previous url, help me to stop concatenating


this is my previouse url - http://127.0.0.1:8000/viewbook/8/viewchapter/57/

this is the url I want to redirect - http://127.0.0.1:8000/viewbook/8/viewchapter/57/

but its redirect me to this 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)

I think the problem is with this line

return redirect('viewchapter/%i/' %chapt.id)

I change it to return HttpResponseRedirect('viewchapter/%i/' %chapt.id)

but bith of them are giving me same result like this

The current path, viewbook/9/viewchapter/58/, didn’t match any of these.


Solution

  • Two problems detected:

    • relative URL which can be fixed with leading / in redirect call
    • redirect function is used not in django way

    Redirect can accept hardcoded URLs however in your case view name with arguments should be passed. As Django docs say redirect can accept view or URL pattern name and arguments:

    return redirect('some-view-name', foo='bar')

    URL will be built by reversing URL pattern you defined in urls.py

    In your case it will be

    return redirect('viewchapter', chapt.id)

    or

    return redirect('viewchapter', id=chapt.id)