You can declare an attribute on your ModelForm
class, called formfield_callback
. This should be a function which takes a Django model Field
instance as an argument, and returns a form Field
instance to represent it in the form.
Then all you have to do is look to see if the model field passed in is an instance of DateField
and, if so, return your custom field/widget. If not, the model field will have a method named formfield
that you can call to return its default form field.
So, something like:
def make_custom_datefield(f):
if isinstance(f, models.DateField):
# return form field with your custom widget here...
else:
return f.formfield(**kwargs)
class SomeForm(forms.ModelForm)
formfield_callback = make_custom_datefield
class Meta:
# normal modelform stuff here...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…