Denigma
hevok @hevok September 14, 2012
#django #form #tutorial

Submitting Data via a Form

This is a simple demonstration on how to submit data via a form into a database. It provides the minimal steps to be performed to accomplish this:

  1. Create the model which is the code interface to the data source (database).
  2. Create the form. Forms are used for processing input data (validation, error reporting, etc.).
  3. Create the view. The view links the a url pattern to a template.
  4. Create the template which is the html returned to the browser.

models.py:

from django.db import models

CHOICES = (1:'small', 2:'medium', 3:'huge')

class SimpleColumn(models.Model):
    column = models.CharFiedl(max_length=255, choices=CHOICES)

forms.py:

from django import forms

class Simple ColumnForm(forms.ModelForm):
    class Meta: model = SimpleColumn

views.py:

from django.shortcuts import render from forms import SimpleColumnForm

def view_column(request):
    if request.method = "POST":
        form = SimpleColumnForm(request.POST)
        if form.is_valid():
            form.save()
        else: form = SimpleColumnForm()
    return render(request, 'view_column.html', {'form': form})

view.html:

{% csrf_token %}
{{ form }}
Save>