In Django its very simple to use the Django forms and create a very simple application using django forms.
Example: Add to number using Djnago forms
forms.py
from django import forms
class Output(forms.Form):
input1 = forms.FloatField()
View.py
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from mysite.add.forms import *
from django.template import RequestContext
from django.core.urlresolvers import reverse
def add(request):
if request.method == 'POST':
form = Output(request.POST)
if form.is_valid():
cd = form.cleaned_data
input1 = cd['input1']
input2 = cd['input2']
output = input1 + input2
return render_to_response('add/output.html', {'form':form, 'input1': input1, 'input2':input2, 'output':output}, context_instance=RequestContext(request))
else:
form = Output()
return render_to_response('add/add.html', {'form': form}, context_instance=RequestContext(request))
Templates used
add.html
<html>
<head>
<title>Add Numbers</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="/media/css/base.css" />
<h1>Add Two Number Application </h1>
<br>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<h2> Fill Data
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output.html
<html>
<head>
<title>Thanks</title>
</head>
<link rel="stylesheet" type="text/css" href="http://arce.sarovar.org/css/rai.css" />
<body>
<h1>Thanks</h1>
<ul>
<li>First Value = {{input1}}
<li>Second Value = {{input2}}
<li> Output = {{output}}
</body>
Very nice to see this post; Also please add how to run this webapp on django. It will be very helpful for beginners like us.
ReplyDeleteFirst you need to create project using command :
Delete$django-admin.py startproject mysite
Check mysite folder and do configuration settings in "settings.py" file.
Then create applications "python manage.py startapp add"
move above files "forms.py" and "views.py" in apptication folder and template file in template path.
For more information you need to go through basic django tutorials: https://docs.djangoproject.com/en/1.5/intro/tutorial01/
Hello ,
DeleteNice and Simple Example
How can I call add Page after I run py manage.py runserver
can you please Zip the example and upload it?!
where to put.....Output.html file
DeleteIn templete folder
Deletewhere is urls.py
ReplyDeleteIn Django project directory. Or you search in folders
Deletestructure your code properly..... unstructured format of your code ..... create problem to your user..... and please share sequence of command sothat anybody can run this simple addition program.....Thanks.... your effort is valuable...... i salute....
ReplyDeleteThanks, for the Feedback. Will Improve
Delete