Saturday, September 4, 2010

Django application : Add two number using forms

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
from django import forms
class Output(forms.Form):
input1 = forms.FloatField()
input2 = forms.FloatField()
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))
form = Output()
return render_to_response('add/add.html', {'form': form}, context_instance=RequestContext(request))

Templates used

<title>Add Numbers</title>
<link rel="stylesheet" type="text/css" href="/media/css/base.css" />
<h1>Add Two Number Application </h1>
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
{% endif %}
<h2> Fill Data
<form action="" method="post">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="Submit">

<link rel="stylesheet" type="text/css" href="" />
<li>First Value = {{input1}}
<li>Second Value = {{input2}}
<li> Output = {{output}}


  1. 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.

    1. First you need to create project using command :
      $ startproject mysite

      Check mysite folder and do configuration settings in "" file.

      Then create applications "python startapp add"
      move above files "" and "" in apptication folder and template file in template path.

      For more information you need to go through basic django tutorials: