Reputation: 77
I am sure this is a silly question but I am trying to understand how forms work in django and I am confused about the action attribute in the template and the httpresponseredirect in views.py
I have the following template:
<form action="/play_outcomes/output/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
And the following view:
def getinput(request):
if request.method == 'POST':
form = get_data(request.POST)
if form.is_valid():
down = form.cleaned_data['get_down']
ytg = form.cleaned_data['get_ytg']
yfog = form.cleaned_data['get_yfog']
return HttpResponseRedirect('/thanks/')
else:
form = get_data()
return render(request, 'play_outcomes/getinput.html', {'form': form})
And finally in forms.py
class get_data(forms.Form):
get_down = forms.IntegerField(label = "Enter a down")
get_ytg = forms.IntegerField(label = "Enter yards to go")
get_yfog = forms.IntegerField(label = "Enter yards from own goal")
When I go to play_outcomes/getinput
my form comes up. When I press 'submit' it directs shows the play_outcomes/output
page, presumably because that is what is specified by the <form action
variable.
Anyway, my question is what is the purpose of the return HttpResponseRedirect('/thanks/')
after it has checked form.is_valid()
. This is TRUE
so it must execute this code. But this return seems redundant.
Please can someone enlighten me on what the return
in the views.py
is doing
Upvotes: 0
Views: 47
Reputation: 1442
Try replacing the form action with action=""
. Everything should continue working normally, since your view handles both GET requests (to show an empty form) and POST requests (to process when a form is submitted). When you press "Submit", your browser is sending the form data back to the exact same place it got the original web page from. Same URL, same view (getinput()
), same template file (play_outcomes/getinput.html
).
Normally, right before that HttpResponseRedirect()
part, you'd include some logic to save the content of that form, email a user, do some calculation, etc. At that point, since the user is all done with that page, you typically redirect them to somewhere else on your site.
Edit: empty action
Upvotes: 2