Return a django.forms.Field instance for this field.
(self, form_class=None, choices_form_class=None, **kwargs)
| 1140 | setattr(instance, self.name, data) |
| 1141 | |
| 1142 | def formfield(self, form_class=None, choices_form_class=None, **kwargs): |
| 1143 | """Return a django.forms.Field instance for this field.""" |
| 1144 | defaults = { |
| 1145 | "required": not self.blank, |
| 1146 | "label": capfirst(self.verbose_name), |
| 1147 | "help_text": self.help_text, |
| 1148 | } |
| 1149 | if self.has_default(): |
| 1150 | if callable(self.default): |
| 1151 | defaults["initial"] = self.default |
| 1152 | defaults["show_hidden_initial"] = True |
| 1153 | else: |
| 1154 | defaults["initial"] = self.get_default() |
| 1155 | if self.choices is not None: |
| 1156 | # Fields with choices get special treatment. |
| 1157 | include_blank = self.blank or not ( |
| 1158 | self.has_default() or "initial" in kwargs |
| 1159 | ) |
| 1160 | defaults["choices"] = self.get_choices(include_blank=include_blank) |
| 1161 | defaults["coerce"] = self.to_python |
| 1162 | if self.null: |
| 1163 | defaults["empty_value"] = None |
| 1164 | if choices_form_class is not None: |
| 1165 | form_class = choices_form_class |
| 1166 | else: |
| 1167 | form_class = forms.TypedChoiceField |
| 1168 | # Many of the subclass-specific formfield arguments (min_value, |
| 1169 | # max_value) don't apply for choice fields, so be sure to only pass |
| 1170 | # the values that TypedChoiceField will understand. |
| 1171 | for k in list(kwargs): |
| 1172 | if k not in ( |
| 1173 | "coerce", |
| 1174 | "empty_value", |
| 1175 | "choices", |
| 1176 | "required", |
| 1177 | "widget", |
| 1178 | "label", |
| 1179 | "initial", |
| 1180 | "help_text", |
| 1181 | "error_messages", |
| 1182 | "show_hidden_initial", |
| 1183 | "disabled", |
| 1184 | ): |
| 1185 | del kwargs[k] |
| 1186 | defaults.update(kwargs) |
| 1187 | if form_class is None: |
| 1188 | form_class = forms.CharField |
| 1189 | return form_class(**defaults) |
| 1190 | |
| 1191 | def value_from_object(self, obj): |
| 1192 | """Return the value of this field in the given model instance.""" |