ModelForm Basics
Creating a ModelForm
A ModelForm's Meta class points at a model and lists which fields to turn into form fields.
Example: Creating a ModelForm
A ModelForm's Meta class points at a model and lists which fields to turn into form fields.
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'body']
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Using __all__ Carefully
fields = __all__ includes every model field, which is convenient but can expose fields you meant to keep internal.
Warning: Prefer listing fields explicitly for models with sensitive or internal-only fields.
Example: Using __all__ Carefully
fields = __all__ includes every model field, which is convenient but can expose fields you meant to keep internal.
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__'
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Excluding Fields Instead
exclude lists fields to leave out, keeping every other model field on the form automatically.
Example: Excluding Fields Instead
exclude lists fields to leave out, keeping every other model field on the form automatically.
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
exclude = ['created_at']
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
- Manually redeclaring every field a model already has instead of letting ModelForm generate them.
- Forgetting the Meta class's fields list, which means the form silently has zero fields.
- Using fields = __all__ on a form tied to sensitive models, accidentally exposing fields that should stay hidden.
- ModelForm generates form fields automatically from a model's field definitions.
- A Meta inner class specifies which model and which fields to include.
- ModelForm reduces duplication between your models.py and forms.py.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: