How To Create A Form In Django
Typical workflow for creating a Django web form
Published:
Last modified:
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 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
# 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
- Forms API https://docs.djangoproject.com/en/1.9/ref/forms/api/#module-django.forms
- Forms tutorial https://docs.djangoproject.com/en/1.9/topics/forms/
- New Forms https://docs.djangoproject.com/en/1.9/topics/forms/
- Forms from models https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/
comments powered by Disqus
- Adding a Cancel button in Django class-based views, editing views and formsJuly 15, 2019
- Using Django Model Primary Key in Custom Forms THE RIGHT WAYJuly 13, 2019
- Django formset handling with class based views, custom errors and validationJuly 4, 2019
- How To Use Bootstrap 4 In Django FormsMay 25, 2018
- Understanding Django FormsApril 30, 2018
- How To Create A Form In Django
Articles
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
·