Django表单工作原理及action属性与HttpResponseRedirect疑问
action and HttpResponseRedirect Hey JohnB, let’s break down how these two pieces work together— I’ve wrestled with this exact confusion when I was learning Django, so I get where you’re coming from.
First: The <form> action Attribute
This isn’t even Django-specific—it’s core HTML! The action tells your browser where to send the form data when the user clicks "Submit".
- In your case, you’ve set
actiontoplay_outcomes/output, so when someone submits the form, their browser sends a POST request (by default, unless you specifymethod="GET") to that URL path. - If you leave
actionempty (like<form method="POST">), the form will submit back to the same URL that rendered it—so in your scenario, that’d beplay_outcomes/getinput. - Pro tip in Django: Instead of hardcoding the path, use the
{% url %}template tag to reference your URL pattern name (e.g.,action="{% url 'play_outcomes:output' %}"). This avoids broken links if you ever change your URL paths later.
Next: HttpResponseRedirect in Views
Once your form data hits the view tied to play_outcomes/output, you’ll process it (validate via your forms.py class, save data, etc.). Then comes HttpResponseRedirect—this is Django’s way of telling the browser to navigate to a new URL after processing the form.
Why is this important? It’s part of the Post/Redirect/Get (PRG) pattern, which solves a common problem:
- If you just return a template directly from your POST view, the user hitting "Refresh" would resend the POST request (and re-submit the form!).
- By redirecting, you send the browser a GET request to the new URL—so refreshing only reloads that GET page, no duplicate form submissions.
Example Flow for Your Setup
- User visits
play_outcomes/getinput(GET request) → your view renders the form template. - User fills out the form, clicks Submit → browser sends POST data to
play_outcomes/output(as specified byaction). - Your
outputview validates the form data, does whatever processing you need (save to DB, calculate results, etc.). - Instead of returning a template directly, you use
HttpResponseRedirectto send the user to a results page (e.g.,play_outcomes/results). - The browser loads the results page via GET—no risk of re-submitting the form if the user refreshes.
Common Confusion to Clear Up
You might be wondering: "Do I have to use HttpResponseRedirect?" Technically no, but it’s a best practice you should follow to avoid user frustration and duplicate data.
Also, note that HttpResponseRedirect takes a URL path (or a reverse-resolved URL using reverse() in your view). For example:
from django.shortcuts import redirect, reverse def output_view(request): if request.method == 'POST': form = YourForm(request.POST) if form.is_valid(): # process your form data here return redirect(reverse('play_outcomes:results')) # handle invalid form or unexpected GET requests return redirect(reverse('play_outcomes:getinput'))
内容的提问来源于stack exchange,提问作者JohnB

