Ticket #11940: modelform-callable-default.patch
File modelform-callable-default.patch, 3.1 KB (added by , 15 years ago) |
---|
-
django/db/models/fields/__init__.py
313 313 "Returns a django.forms.Field instance for this database Field." 314 314 defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} 315 315 if self.has_default(): 316 defaults['initial'] = self.get_default()317 316 if callable(self.default): 317 defaults['initial'] = self.default 318 318 defaults['show_hidden_initial'] = True 319 else: 320 defaults['initial'] = self.get_default() 319 321 if self.choices: 320 322 # Fields with choices get special treatment. 321 323 include_blank = self.blank or not (self.has_default() or 'initial' in kwargs) -
django/forms/fields.py
107 107 messages.update(error_messages or {}) 108 108 self.error_messages = messages 109 109 110 def _get_initial(self): 111 if callable(self._initial): 112 return self._initial() 113 return self._initial 114 115 def _set_initial(self, value): 116 self._initial = value 117 118 initial = property(_get_initial, _set_initial) 119 110 120 def clean(self, value): 111 121 """ 112 122 Validates the given value and returns its "cleaned" value as an -
tests/regressiontests/forms/models.py
15 15 class BoundaryModel(models.Model): 16 16 positive_integer = models.PositiveIntegerField(null=True, blank=True) 17 17 18 callable_default_value = 1 19 def callable_default(): 20 global callable_default_value 21 callable_default_value = callable_default_value + 1 22 return callable_default_value 23 18 24 class Defaults(models.Model): 19 25 name = models.CharField(max_length=255, default='class default value') 20 26 def_date = models.DateField(default = datetime.date(1980, 1, 1)) 21 27 value = models.IntegerField(default=42) 28 callable_default = models.IntegerField(default=callable_default) 22 29 23 30 class ChoiceModel(models.Model): 24 31 """For ModelChoiceField and ModelMultipleChoiceField tests.""" … … 85 92 datetime.date(1980, 1, 1) 86 93 >>> DefaultsForm().fields['value'].initial 87 94 42 95 >>> DefaultsForm().fields['callable_default'].initial != DefaultsForm().fields['callable_default'].initial 96 True 88 97 89 98 In a ModelForm that is passed an instance, the initial values come from the 90 99 instance's values, not the model's defaults. … … 102 111 ... name = CharField(max_length=255) 103 112 ... class Meta: 104 113 ... model = Defaults 105 ... exclude = ['name' ]114 ... exclude = ['name', 'callable_default'] 106 115 >>> f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)}) 107 116 >>> f.is_valid() 108 117 True