Django simplify and automates the process to create a form in simple steps.

Overview

A tipical workflow when creating a form in Django consists of these three steps:

graph TB a[Create a Form class that defines its fields]-->b b[Create the view to display the form and process received data]-->c c[create the template to show the form]

Creating the form

A form can be defined from scratch or take the field defitions from Model classes.

graph TB form-->has_model{"from a model"} has_model-- no -->scratch["Inherits from django.forms.Form"] has_model-- yes -->model["Inherits from django.forms.ModelForm"] scratch-->fields["Define fields using django.forms.*Field"]

New Form

# forms.py
from django import forms

class ContactForm(forms.Form):
    name = forms.CharField(label='Full name', max_length=70)

From Model

from django.forms import ModelForm
from myapp.models import News

class ArticleForm(ModelForm):
    class Meta:
        model = News
    fields = ['title', 'content']

Creating an empty form to add an article.

form = ArticleForm()

Creating a form to change an existing article.

article = Article.objects.get(pk=1)
form = ArticleForm(instance=article)

References

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.