Home > Enterprise >  Redirecting the user to the same page after POST
Redirecting the user to the same page after POST

Time:07-02

I'm building a tournament organizing tool but I have run into an issue.

I have a view called index (currently the only view) that shows the tournament leaderboard as well as a table of unfinished matches and a table of finished matches. For each of the unfinished matches I have added an input field for each player where the user can type the scores. Each match also has a submit button. What I want to happen is that when the submit button is clicked, the match is finished and the match result (the scores in the input fields) are saved to the database. I then want the user to see the same page again (with the match moved from unfinished to finished). The problem I'm having is getting the player to be redirected to the same page again. I've tried looking around for similar questions and the answers to them and I have tried a couple of different things like

if request.method == "POST":
    return render(request, './')

or

if request.method == "POST":
    return redirect(request.path)

or

if request.method == "POST":
    return index(request)

all of them redirect me to /index.html which does not exist - my urlpatterns look like this

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    ]

I could really use some help identifying what I'm doing wrong here. Thanks in advance

CodePudding user response:

You could use redirect() with the name attribute set on the url like:

if request.method == "POST":
     return redirect("index") # or -> return redirect("/")

However, if you're using an app_name, you would want to say:

if request.method == "POST":
     return redirect("app_name:index")

I'm not so sure if having a return statement within the if request.method == "POST": block; going to the same page makes much sense in this case since you would want the user to stay on the same page. I assume you already have a return statement outside of the if request.method == "POST": block. Why not just use that alone for this view?

  • Related