django 找不到重定向页面

django not finding redirect page

大家好,我有以下代码,我正在尝试将 GoalUpdate 视图重定向到 GoalPageView,但出现以下错误:

反向 'Goals.views.GoalPageView' 关键字参数 '{'kwargs': {'username': 'admin', 'goal_id': '1'}}' 未找到.尝试了 1 种模式:['people/(?P[^/]+)/goals/(?P<goal_id>[^/]+)/\Z']

我的网址

urlpatterns = [
    path('<username>/goals/',GoalsView,name='Goals'),
    path('<username>/goals/<goal_id>/',GoalPageView,name='Goal Page'),
    path('<username>/goals/<goal_id>/update/',GoalUpdate,name='Goal Update'),
                ]

我的观点:

def GoalPageView(request,username,goal_id):

    some view code

    return render(request,'goal_page.html',context=context)



def GoalUpdate(request,username,goal_id):

    Some View Code
    
    return redirect(GoalPageView,kwargs={'username':username,'goal_id':goal_id})

redirect 不采用 argskwargs 而是直接使用位置和命名参数,因此:

def GoalUpdate(request, username, goal_id):
    # some view code …
    return redirect('Goal Page', <strong>username=username, goal_id=goal_id</strong>)

Note: Functions are normally written in snake_case, not PascalCase, therefore it is advisable to rename your function to goal_update, not GoalUpdate.

您必须使用 url 的 name,而不是 View 本身。要添加 kwargs 就像你可以使用 reverse_lazy:

return redirect(reverse_lazy('Goal Page', kwargs={'username':username, 'goal_id':goal_id}))

但我认为 Willem 给了你更简单的解决方案。