2019独角兽企业重金招聘Python工程师标准>>>
Field types
The generated Form class will have a form field for every model field. Each model field has a corresponding default form field. For example, a CharField on a model is represented as a CharField on a form. A model ManyToManyField is represented as aMultipleChoiceField. Here is the full list of conversions:
Model field | Form field |
---|---|
AutoField | Not represented in the form |
BigIntegerField | IntegerField with min_value set to -9223372036854775808 andmax_value set to 9223372036854775807. |
BooleanField | BooleanField |
CharField | CharField with max_length set to the model field's max_length |
CommaSeparatedIntegerField | CharField |
DateField | DateField |
DateTimeField | DateTimeField |
DecimalField | DecimalField |
EmailField | EmailField |
FileField | FileField |
FilePathField | CharField |
FloatField | FloatField |
ForeignKey | ModelChoiceField (see below) |
ImageField | ImageField |
IntegerField | IntegerField |
IPAddressField | IPAddressField |
ManyToManyField | ModelMultipleChoiceField (see below) |
NullBooleanField | CharField |
PhoneNumberField | USPhoneNumberField (from django.contrib.localflavor.us) |
PositiveIntegerField | IntegerField |
PositiveSmallIntegerField | IntegerField |
SlugField | SlugField |
SmallIntegerField | IntegerField |
TextField | CharField with widget=forms.Textarea |
TimeField | TimeField |
URLField | URLField with verify_exists set to the model field's verify_exists |
As you might expect, the ForeignKey and ManyToManyField model field types are special cases:
- ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet.
- ManyToManyField is represented by django.forms.ModelMultipleChoiceField, which is a MultipleChoiceField whose choices are a model QuerySet.
In addition, each generated form field has attributes set as follows:
- If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True.
- The form field's label is set to the verbose_name of the model field, with the first character capitalized.
- The form field's help_text is set to the help_text of the model field.
- If the model field has choices set, then the form field's widget will be set to Select, with choices coming from the model field's choices. The choices will normally include the blank choice which is selected by default. If the field is required, this forces the user to make a selection. The blank choice will not be included if the model field has blank=False and an explicitdefault value (the default value will be initially selected instead).
Finally, note that you can override the form field used for a given model field. See Overriding the default field types or widgetsbelow.