This code will generate a Form based on an already existing Model. In Django this is called ModelForm and is a useful feature if you want to quickly create a form that saves data into a database.

Create a model (database table):

from django.db import models
class Regions(models.Model):
    region = models.CharField(max_length=50)
    def __unicode__(self):
        return self.region

Create a form from the model (ModelForm):

from ApplicationName.models import Regions
class AddRegionForm(forms.ModelForm):
    class Meta:
        model = Regions

Create a view that will use the form and model:

def add_region(request):
    # if the form is submitted save the new item
    if request.method == 'POST':
        form = AddRegionForm(request.POST)
        if form.is_valid():
            # either you define the fields
            region = Regions(region=form.cleaned_data['region'])
            # or you just save the whole form
            region =
    # fetch all the regions from the table, ordered by name asc
    regions = Regions.objects.order_by('region')
    context = ({ 'regions': regions })
    # render the template
    return render(request, 'applicationname/regions.html', context)


Leave a Reply

Your email address will not be published. Required fields are marked *