Regnald Terry
Regnald Terry

Reputation: 48

How to redirect to another page that contains ID in django

I have this function in view.py file that i pass an ID on it and it render a certain page

def more_about_child(request,pk):
    child = get_object_or_404(Child_detail,pk=pk)
    academic = Academic.objects.filter(Student_name=child)  
    context={ 
        'child':child, 
        'academic':academic,
    }
    return render(request,'functionality/more/more.html',context)

And this urls.py file belongs to above views.py file

from . import views
from django.urls import path

urlpatterns=[
    #more_about_child
    path('more/<int:pk>/',views.more_about_child,name='more'),
]

Then i have this function that i want to redirect to a page that contain an id in the above urls.py file

def add_academy(request,pk):
    child = get_object_or_404(Child_detail, pk=pk)
    academic = Academic.objects.get(Student_name=child)
    form = AcademicForm(request.POST, instance=academic)
    if form.is_valid():
        form.save()
        return redirect('more') #it fails to redirect to this url,because it contain an ID in it
    else:
        form=AcademicForm()
    context = {
        'academic':academic,
        'child':child,
        'form':form,
    }

Upvotes: 1

Views: 3763

Answers (1)

Nornil
Nornil

Reputation: 101

In order to make redirect with url arguments you can pass keyword arguments to redirect() function. In your case you can call it as:

return redirect('more', pk=pk)

Here is documentation example for such usage: https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#examples (example #2)

Upvotes: 9

Related Questions