我在Django视图中遇到了redirect()问题。
我定义了两个视图,如下所示:# view for managing a user's account
@login_required
@require_http_methods(['GET'])
def view_account(request, updated=False):
context = {
'user': request.user,
'cart_items': ShoppingCartItem.objects.filter(user_key=request.user),
'updated': updated,
}
print("DEBUG: view_account: %s" % updated) # debug
return render(request, 'registration/view_account.html', context)
和# view for updating information about a user's account
@login_required
@require_http_methods(['GET', 'POST'])
def update_account_info(request):
if request.method == 'POST':
# if this is a POST, user has submitted updated information
form = UpdateUserInfoForm(request.POST, instance=request.user)
if form.is_valid():
# if valid, redirect to view_account
form.save()
# return render(request, 'registration/view_account.html', context)
return redirect('/view_account', updated=True)
对于url,这些函数看起来如下所示:path('view_account', views.view_account, name='view_account'),
path('update_account', views.update_account_info, name='update_account'),
在第二个函数中,我试图将用户重定向到view_account()视图,并传入updated=True参数,通知用户他们的信息已更新,当我运行它时,不会改变updated的默认值。
你可以看到,我在view_account()视图中有一个调试语句,输出如下:[04/Nov/2019 16:51:33]"POST /update_account HTTP/1.1" 302 0
DEBUG: view_account: False
[04/Nov/2019 16:51:33]"GET /view_account HTTP/1.1" 200 1247