Django redirect() doesn't redirect but rather refreshes the same page
view.py
@login_required(login_url='index', redirect_field_name=None)
def new_character(request):
if request.method == 'POST':
character_form = CharacterForm(request.POST)
if character_form.is_valid():
new_character = character_form.save(commit=False)
new_character.creator = request.user
new_character.save()
# If new_character has a primary key (pk) then it
# means it was saved to the database.
if new_character.pk:
# TODO: For some reason this doesn't work.
redirect('list_characters')
else:
character_form = CharacterForm()
return render(request, 'characters/new-character.html', {'character_form': character_form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.list_characters, name='list_characters'),
path('new/', views.new_character, name='new_character'),
]
I checked and new_character.pk
is coerced to True. However, the redirect doesn't happen and instead the same page is simply refreshed.
The issue here is that you are not returning the redirect
, which results in the return render(request, 'characters/new-character.html'...
being hit, changing from:
redirect('list_characters')
To:
return redirect('list_characters')
Should solve the issue