How To Create A Form In Django

Typical workflow for creating a Django web form

Last modified:


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 definitions 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

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)


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.
comments powered by Disqus

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

Clutter-free software concepts.
Translations English Espa簽ol

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme