如何重定向到包含django中的ID的另一个页面

时间:2020-03-31 13:50:16

标签: python django django-views django-templates django-urls

我在view.py文件中具有此功能,在该文件上传递了ID,它可以呈现特定页面

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)

这个urls.py文件属于上述views.py文件

from . import views
from django.urls import path

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

然后我具有要重定向到上述urls.py文件中包含ID的页面的功能

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,
    }

1 个答案:

答案 0 :(得分:3)

为了使用url参数进行重定向,您可以将关键字参数传递给redirect()函数。您可以将其称为:

return redirect('more', pk=pk)

以下是这种用法的文档示例:https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#examples(示例#2)