Posts Tagged ‘Models’

ModelForms in Django

November 13th, 2008

I was supposed to create a form for entry into the database and I found a simple ModelForms way as listed in the Django documents.

I made use of 4 files – forms.py, models.py, views.py and the html

1. Starting off with models.py and database is assume to be validated and syncdb is used to create the db.

from django.db import models
from django.contrib.auth.models import User

Class Sample (models.Model):

user = models.ForeignKey(User)

number  = models.FloatField()

label = models.CharField(max_length=30)

2. Once Db is setup properly, forms.py is setup

from django import newforms as forms

from models import Sample
from django.forms import ModelForm

Class SampleForm(ModelForm):

class Meta:
model = Sample
fields = (‘number’, ‘user’ )

Thus, in here, the forms will make use of the models.py and those fields indicated will be popluted in the Form

3. Next, We setup the views.py

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})

Urls.py is assumed to setup properly.

4. and lastly, the sample.htm is done

<form action=”.” method=”POST”>
<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 done.. thats all you need to do to create a form in Django using database and some manipulation.

VN:F [1.9.6_1107]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.6_1107]
Rating: 0 (from 0 votes)
DiggTwitterTechnorati FavoritesRedditNewsVineFacebookShare
Get Adobe Flash playerPlugin by wpburn.com wordpress themes