0
# Forms System
1
2
Django's forms system provides HTML form generation, data validation, and processing capabilities with comprehensive type support for form fields, widgets, and validation logic.
3
4
## Core Imports
5
6
```python
7
# Form base classes
8
from django import forms
9
from django.forms import Form, ModelForm, BaseForm
10
11
# Form fields
12
from django.forms import (
13
CharField, TextField, IntegerField, FloatField, DecimalField,
14
BooleanField, NullBooleanField, DateField, DateTimeField, TimeField,
15
EmailField, URLField, SlugField, RegexField, UUIDField,
16
ChoiceField, MultipleChoiceField, ModelChoiceField, ModelMultipleChoiceField,
17
FileField, ImageField, TypedChoiceField, TypedMultipleChoiceField
18
)
19
20
# Form widgets
21
from django.forms.widgets import (
22
TextInput, Textarea, NumberInput, EmailInput, URLInput,
23
PasswordInput, HiddenInput, CheckboxInput, Select, SelectMultiple,
24
RadioSelect, CheckboxSelectMultiple, FileInput, ClearableFileInput,
25
DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget
26
)
27
28
# Form validation
29
from django.forms import ValidationError
30
from django.core.exceptions import ValidationError as CoreValidationError
31
32
# Form utilities
33
from django.forms.formsets import formset_factory, modelformset_factory, inlineformset_factory
34
```
35
36
## Capabilities
37
38
### Form Base Classes
39
40
Core form classes providing structure for HTML form generation and data processing.
41
42
```python { .api }
43
class BaseForm:
44
"""Base form implementation with field management and validation."""
45
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
46
initial=None, error_class=None, label_suffix=None,
47
empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None): ...
48
49
def is_valid(self) -> bool: ...
50
def full_clean(self) -> None: ...
51
def clean(self) -> dict: ...
52
def has_changed(self) -> bool: ...
53
def changed_data(self) -> list: ...
54
def add_error(self, field: str, error) -> None: ...
55
def has_error(self, field: str, code: str = None) -> bool: ...
56
def non_field_errors(self): ...
57
58
class Form(BaseForm):
59
"""Standard form class for HTML form handling."""
60
def __init__(self, data=None, files=None, **kwargs): ...
61
62
class BaseModelForm(BaseForm):
63
"""Base class for forms tied to model instances."""
64
def __init__(self, data=None, files=None, instance=None, **kwargs): ...
65
def save(self, commit: bool = True): ...
66
67
class ModelForm(BaseModelForm):
68
"""Form automatically generated from a Django model."""
69
70
class Meta:
71
model = None
72
fields = None
73
exclude = None
74
widgets = None
75
localized_fields = None
76
labels = None
77
help_texts = None
78
error_messages = None
79
field_classes = None
80
```
81
82
### Form Fields
83
84
Field types for form input validation and processing.
85
86
```python { .api }
87
class Field:
88
"""Base field class for form fields."""
89
def __init__(self, required: bool = True, widget=None, label: str = None,
90
initial=None, help_text: str = '', error_messages: dict = None,
91
show_hidden_initial: bool = False, validators: list = None,
92
localize: bool = False, disabled: bool = False, label_suffix=None): ...
93
94
def clean(self, value): ...
95
def validate(self, value) -> None: ...
96
def run_validators(self, value) -> None: ...
97
def to_python(self, value): ...
98
def has_changed(self, initial, data) -> bool: ...
99
100
class CharField(Field):
101
"""Character/string input field."""
102
def __init__(self, max_length: int = None, min_length: int = None, strip: bool = True, **kwargs): ...
103
104
class IntegerField(Field):
105
"""Integer input field."""
106
def __init__(self, max_value: int = None, min_value: int = None, **kwargs): ...
107
108
class FloatField(Field):
109
"""Floating point number input field."""
110
def __init__(self, max_value: float = None, min_value: float = None, **kwargs): ...
111
112
class DecimalField(Field):
113
"""Decimal number input field."""
114
def __init__(self, max_value=None, min_value=None, max_digits: int = None, decimal_places: int = None, **kwargs): ...
115
116
class BooleanField(Field):
117
"""Boolean checkbox field."""
118
def __init__(self, **kwargs): ...
119
120
class NullBooleanField(Field):
121
"""Three-state boolean field (True/False/None)."""
122
def __init__(self, **kwargs): ...
123
124
class EmailField(CharField):
125
"""Email address input field with validation."""
126
def __init__(self, **kwargs): ...
127
128
class URLField(CharField):
129
"""URL input field with validation."""
130
def __init__(self, **kwargs): ...
131
132
class SlugField(CharField):
133
"""Slug input field for URL slugs."""
134
def __init__(self, **kwargs): ...
135
136
class RegexField(CharField):
137
"""Text field with regex validation."""
138
def __init__(self, regex, **kwargs): ...
139
140
class UUIDField(CharField):
141
"""UUID input field."""
142
def __init__(self, **kwargs): ...
143
144
class DateField(Field):
145
"""Date input field."""
146
def __init__(self, input_formats: list = None, **kwargs): ...
147
148
class TimeField(Field):
149
"""Time input field."""
150
def __init__(self, input_formats: list = None, **kwargs): ...
151
152
class DateTimeField(Field):
153
"""Date and time input field."""
154
def __init__(self, input_formats: list = None, **kwargs): ...
155
156
class DurationField(Field):
157
"""Duration/timedelta input field."""
158
def __init__(self, **kwargs): ...
159
160
class ChoiceField(Field):
161
"""Single choice selection field."""
162
def __init__(self, choices=(), **kwargs): ...
163
164
class TypedChoiceField(ChoiceField):
165
"""Choice field with type coercion."""
166
def __init__(self, coerce=None, empty_value: str = '', **kwargs): ...
167
168
class MultipleChoiceField(ChoiceField):
169
"""Multiple choice selection field."""
170
def __init__(self, **kwargs): ...
171
172
class TypedMultipleChoiceField(MultipleChoiceField):
173
"""Multiple choice field with type coercion."""
174
def __init__(self, coerce=None, **kwargs): ...
175
176
class FileField(Field):
177
"""File upload field."""
178
def __init__(self, max_length: int = None, allow_empty_file: bool = False, **kwargs): ...
179
180
class ImageField(FileField):
181
"""Image file upload field with validation."""
182
def __init__(self, **kwargs): ...
183
184
class FilePathField(ChoiceField):
185
"""File path selection field."""
186
def __init__(self, path: str, match: str = None, recursive: bool = False,
187
allow_files: bool = True, allow_folders: bool = False, **kwargs): ...
188
189
class JSONField(CharField):
190
"""JSON data input field."""
191
def __init__(self, encoder=None, decoder=None, **kwargs): ...
192
```
193
194
### Composite Fields
195
196
Fields that combine multiple inputs or handle complex data structures.
197
198
```python { .api }
199
class MultiValueField(Field):
200
"""Field that aggregates multiple fields."""
201
def __init__(self, fields: tuple, require_all_fields: bool = True, **kwargs): ...
202
def compress(self, data_list): ...
203
204
class ComboField(Field):
205
"""Field that validates against multiple field types."""
206
def __init__(self, fields: list, **kwargs): ...
207
208
class SplitDateTimeField(MultiValueField):
209
"""Date and time field split into separate inputs."""
210
def __init__(self, input_date_formats: list = None, input_time_formats: list = None, **kwargs): ...
211
```
212
213
### Model-Related Fields
214
215
Fields specifically designed for working with Django models.
216
217
```python { .api }
218
class ModelChoiceField(ChoiceField):
219
"""Choice field populated from model QuerySet."""
220
def __init__(self, queryset, empty_label: str = "---------", to_field_name: str = None, **kwargs): ...
221
222
class ModelMultipleChoiceField(MultipleChoiceField):
223
"""Multiple choice field populated from model QuerySet."""
224
def __init__(self, queryset, **kwargs): ...
225
```
226
227
### Form Widgets
228
229
UI components for rendering form fields in HTML.
230
231
```python { .api }
232
class Widget:
233
"""Base widget class for HTML form controls."""
234
def __init__(self, attrs: dict = None): ...
235
def render(self, name: str, value, attrs: dict = None, renderer=None) -> str: ...
236
def value_from_datadict(self, data: dict, files: dict, name: str): ...
237
def format_value(self, value): ...
238
239
class Input(Widget):
240
"""Base class for HTML input elements."""
241
input_type: str = None
242
template_name: str = 'django/forms/widgets/input.html'
243
244
class TextInput(Input):
245
"""Text input widget."""
246
input_type: str = 'text'
247
248
class NumberInput(Input):
249
"""Number input widget."""
250
input_type: str = 'number'
251
252
class EmailInput(Input):
253
"""Email input widget."""
254
input_type: str = 'email'
255
256
class URLInput(Input):
257
"""URL input widget."""
258
input_type: str = 'url'
259
260
class PasswordInput(Input):
261
"""Password input widget."""
262
input_type: str = 'password'
263
def __init__(self, attrs: dict = None, render_value: bool = False): ...
264
265
class HiddenInput(Input):
266
"""Hidden input widget."""
267
input_type: str = 'hidden'
268
269
class DateInput(Input):
270
"""Date input widget."""
271
input_type: str = 'date'
272
format_key: str = 'DATE_INPUT_FORMATS'
273
274
class DateTimeInput(Input):
275
"""DateTime input widget."""
276
input_type: str = 'datetime-local'
277
format_key: str = 'DATETIME_INPUT_FORMATS'
278
279
class TimeInput(Input):
280
"""Time input widget."""
281
input_type: str = 'time'
282
format_key: str = 'TIME_INPUT_FORMATS'
283
284
class Textarea(Widget):
285
"""Multi-line text input widget."""
286
template_name: str = 'django/forms/widgets/textarea.html'
287
def __init__(self, attrs: dict = None): ...
288
289
class CheckboxInput(Widget):
290
"""Checkbox input widget."""
291
template_name: str = 'django/forms/widgets/checkbox.html'
292
def __init__(self, attrs: dict = None, check_test=None): ...
293
294
class Select(Widget):
295
"""Select dropdown widget."""
296
template_name: str = 'django/forms/widgets/select.html'
297
def __init__(self, attrs: dict = None, choices=()): ...
298
299
class NullBooleanSelect(Select):
300
"""Select widget for null boolean field."""
301
302
class SelectMultiple(Select):
303
"""Multiple selection widget."""
304
template_name: str = 'django/forms/widgets/select_multiple.html'
305
def __init__(self, attrs: dict = None, choices=()): ...
306
307
class RadioSelect(Select):
308
"""Radio button selection widget."""
309
template_name: str = 'django/forms/widgets/radio.html'
310
311
class CheckboxSelectMultiple(SelectMultiple):
312
"""Multiple checkbox selection widget."""
313
template_name: str = 'django/forms/widgets/checkbox_select.html'
314
315
class FileInput(Input):
316
"""File upload widget."""
317
input_type: str = 'file'
318
template_name: str = 'django/forms/widgets/file.html'
319
320
class ClearableFileInput(FileInput):
321
"""File input with clear option."""
322
template_name: str = 'django/forms/widgets/clearable_file_input.html'
323
```
324
325
### Composite Widgets
326
327
Widgets that combine multiple form controls.
328
329
```python { .api }
330
class MultiWidget(Widget):
331
"""Widget that combines multiple widgets."""
332
def __init__(self, widgets: tuple, attrs: dict = None): ...
333
def decompress(self, value): ...
334
335
class SplitDateTimeWidget(MultiWidget):
336
"""Widget for split date and time inputs."""
337
def __init__(self, attrs: dict = None, date_format: str = None, time_format: str = None): ...
338
339
class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
340
"""Hidden widget for split date and time."""
341
342
class SelectDateWidget(Widget):
343
"""Date selection using separate dropdowns."""
344
def __init__(self, attrs: dict = None, years: list = None, months: dict = None, empty_label: str = None): ...
345
```
346
347
### Form Utilities
348
349
Utility functions for form processing and generation.
350
351
```python { .api }
352
def formset_factory(form, formset=None, extra: int = 1, can_order: bool = False,
353
can_delete: bool = False, max_num: int = None, min_num: int = None,
354
validate_max: bool = False, validate_min: bool = False, absolute_max: int = None) -> type:
355
"""Create a FormSet class for the given form class."""
356
357
def modelformset_factory(model, form=None, formfield_callback=None, formset=None,
358
extra: int = 1, can_delete: bool = False, can_order: bool = False,
359
max_num: int = None, min_num: int = None, fields=None, exclude=None,
360
widgets=None, validate_max: bool = False, validate_min: bool = False,
361
localized_fields=None, labels=None, help_texts=None,
362
error_messages=None, absolute_max: int = None, field_classes=None) -> type:
363
"""Create a ModelFormSet class for the given model."""
364
365
def inlineformset_factory(parent_model, model, form=None, formset=None, fk_name: str = None,
366
fields=None, exclude=None, extra: int = 3, can_order: bool = False,
367
can_delete: bool = True, max_num: int = None, min_num: int = None,
368
formfield_callback=None, widgets=None, validate_max: bool = False,
369
validate_min: bool = False, localized_fields=None, labels=None,
370
help_texts=None, error_messages=None, absolute_max: int = None,
371
field_classes=None) -> type:
372
"""Create an InlineFormSet class for the given models."""
373
374
def modelform_factory(model, form=None, fields=None, exclude=None, formfield_callback=None,
375
widgets=None, localized_fields=None, labels=None, help_texts=None,
376
error_messages=None, field_classes=None) -> type:
377
"""Create a ModelForm class for the given model."""
378
379
def fields_for_model(model, fields=None, exclude=None, widgets=None, formfield_callback=None,
380
localized_fields=None, labels=None, help_texts=None, error_messages=None,
381
field_classes=None, apply_limit_choices_to: bool = True) -> dict:
382
"""Return form fields for the given model."""
383
384
def model_to_dict(instance, fields=None, exclude=None) -> dict:
385
"""Convert model instance to dictionary."""
386
387
def all_valid(formsets: list) -> bool:
388
"""Validate all formsets in a list."""
389
```
390
391
### FormSets
392
393
Collections of forms for handling multiple instances.
394
395
```python { .api }
396
class BaseFormSet:
397
"""Base class for form collections."""
398
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
399
initial=None, error_class=None, form_kwargs=None): ...
400
401
def is_valid(self) -> bool: ...
402
def full_clean(self) -> None: ...
403
def clean(self) -> None: ...
404
def has_changed(self) -> bool: ...
405
def add_error(self, field: str, error) -> None: ...
406
def non_form_errors(self): ...
407
def total_form_count(self) -> int: ...
408
def initial_form_count(self) -> int: ...
409
410
class BaseModelFormSet(BaseFormSet):
411
"""Base class for model formsets."""
412
def __init__(self, data=None, files=None, queryset=None, **kwargs): ...
413
def save(self, commit: bool = True) -> list: ...
414
def save_existing_objects(self, commit: bool = True) -> list: ...
415
def save_new_objects(self, commit: bool = True) -> list: ...
416
def add_fields(self, form, index: int) -> None: ...
417
418
class BaseInlineFormSet(BaseModelFormSet):
419
"""Base class for inline formsets."""
420
def __init__(self, data=None, files=None, instance=None, **kwargs): ...
421
```
422
423
### Form Validation
424
425
Validation and error handling components.
426
427
```python { .api }
428
class ValidationError(Exception):
429
"""Form validation error."""
430
def __init__(self, message, code: str = None, params: dict = None): ...
431
432
error_dict: dict
433
error_list: list
434
message: str
435
code: str
436
params: dict
437
438
class BoundField:
439
"""Field bound to form data."""
440
def __init__(self, form, field, name: str): ...
441
442
def as_widget(self, widget=None, attrs: dict = None, only_initial: bool = False) -> str: ...
443
def as_text(self, attrs: dict = None, **kwargs) -> str: ...
444
def as_textarea(self, attrs: dict = None, **kwargs) -> str: ...
445
def as_hidden(self, attrs: dict = None, **kwargs) -> str: ...
446
def value(self): ...
447
def label_tag(self, contents: str = None, attrs: dict = None, label_suffix=None) -> str: ...
448
449
class BoundWidget:
450
"""Widget bound to form data."""
451
def __init__(self, parent_widget, data, renderer): ...
452
```
453
454
### Media Handling
455
456
CSS and JavaScript asset management for forms and widgets.
457
458
```python { .api }
459
class Media:
460
"""CSS and JavaScript media definition."""
461
def __init__(self, media=None, css: dict = None, js: tuple = None): ...
462
463
def render(self) -> str: ...
464
def render_js(self) -> list: ...
465
def render_css(self) -> list: ...
466
def absolute_path(self, path: str) -> str: ...
467
468
css: dict
469
js: tuple
470
```
471
472
### Form Processing
473
474
Utilities for handling form data and file uploads.
475
476
```python { .api }
477
class MultiValueDict(dict):
478
"""Dictionary that can hold multiple values for the same key."""
479
def __init__(self, key_to_list_mapping=()): ...
480
def getlist(self, key: str, default: list = None) -> list: ...
481
def setlist(self, key: str, list_: list) -> None: ...
482
def appendlist(self, key: str, value) -> None: ...
483
def setlistdefault(self, key: str, default_list: list = None) -> list: ...
484
def lists(self): ...
485
def dict(self) -> dict: ...
486
487
class FileDict(MultiValueDict):
488
"""Dictionary for uploaded files."""
489
490
class QueryDict(MultiValueDict):
491
"""Dictionary for query string and POST data."""
492
def __init__(self, query_string: str = None, mutable: bool = False, encoding: str = None): ...
493
def urlencode(self, safe: str = None) -> str: ...
494
```