Django forms method GET and POST
November 19th, 2008As mentioned in my last entry on ModelForms, i was playing around with ModelForms in Django. I found something interesting in using both the get and post method.
I have 2 pages – one for forms. the other is to confirm values / pay. However, based on the last entry, I didnt really want to save the values in the form after i click submit.
to retract how the form looks like, here is it below:
def sample(request):
if request.method == “POSTâ€:
form = SampleForm(request.POST)
if form.is_valid():
new_Sample = form.save(commit=False)
new_Sample.label = ‘Sample01′
new_Sample.save()
return HttpResponseRedirect(’/contact/thanks/’)
else:
print “no sell requestâ€
form = SampleForm()
return render_to_response(’Sample.htm’, {’form’: form})
So, in order to change it to 2 pages. i changed the form page so it goes to the next page.
<form action=â€sample2†method=â€GETâ€>
<dl>
<dt><label for=â€id_userâ€>user:</label>{% if user.errors %} <span class=â€errorâ€>{{ user.errors|join:â€, †}}</span>{% endif %}</dt>
<dd><input type=â€text†name=â€user†value=â€{{ user }}†size=â€6″></dd>
<dt><label for=â€id_numberâ€>number:</label>{% if number.errors %} <span class=â€errorâ€>{{ number.errors|join:â€, †}}</span>{% endif %}</dt>
<dd> <input type=â€text†name=â€number†value=â€{{ number }}†size=â€6″></dd>
<dt><input type=â€submit†value=â€Submit†/></dt>
and the views is a simple printing of form
def sample(request):
print “no sell requestâ€
form = SampleForm()
return render_to_response(’Sample.htm’, {’form’: form})
Thus, when click on the button submit: it goes to the next page where all the values in the form is sent there. the url should show something like localhost:8000/sample2/?user=weiyang&number=10
and then for sample 2
def sample2(request):
if request.method == “POSTâ€:
form = SampleForm(request.POST)
if form.is_valid():
new_Sample = form.save(commit=False)
new_Sample.label = ‘Sample01′
new_Sample.save()
return HttpResponseRedirect(’/contact/thanks/’)
else:
print “no sell requestâ€
form = SampleForm()
return render_to_response(’Sample2.htm’, {’form’: form})
and my sample2.htm is shown as
<form action=”.” method=”POST”>
<input type=”hidden” size=”10″ name=”user” value=”{{ user }}” />
<input type=”hidden” size=”10″ name=”number” value=”{{ number }}” />
…..posting of values to be seen….</form>
hope this helps.
