I am trying to use the Django message system to send the user back to their previous page. I have a Delete Customer FBV that can be accessed from multiple locations and after deleting the customer I want to send the user back to where they were. If I do this it works well and I get the behavior I expected:
@login_required
def delete_customer(request, custpk):
del_cust = Customer.objects.get(pk=custpk)
returnURL = ''
if request.method == "POST":
storage = get_messages(request)
for message in storage:
returnURL = message.message
storage.used = True
del_cust.delete()
return redirect(returnURL)
context = {
'del_cust': del_cust
}
return render(request, 'delete_customer.html', context)
However, I want to be able to use that returnURL variable both in the If "POST" section and in the context variable to send to the render statement. Why when I do this does it not work?
@login_required
def delete_customer(request, custpk):
del_cust = Customer.objects.get(pk=custpk)
returnURL = ''
storage = get_messages(request)
for message in storage:
returnURL = message.message
storage.used = True
if request.method == "POST":
del_cust.delete()
return redirect(returnURL)
context = {
'del_cust': del_cust,
'returnURL': returnURL
}
return render(request, 'delete_customer.html', context)
Why does this not work? When the redirect hits it says there is nothing to redirect to. How can I set up the returnURL variable at the top of the function and use it in the If "POST" section and in the context variable?
EDIT: I agree, assigning the variable in a loop is bad. Consider the example below. Why is the del_cust variable available within the If..."POST" statement but the urlList variable is not? The first print(urlList) shows me my list with one item (the text of my one message). The second print(urlList) inside the If..."POST" statement shows me an empty list. Why?
@login_required
def delete_customer(request, custpk):
del_cust = Customer.objects.get(pk=custpk)
urlList = []
storage = get_messages(request)
for message in storage:
urlList.append(message.message)
storage.used = True
print(urlList)
if request.method == "POST":
print(urlList)
del_cust.delete()
return redirect('/')
context = {
'del_cust': del_cust
}
return render(request, 'delete_customer.html', context)