Generic views are awesome. Simply specifying a model, sees a lovely default form provided to templates built by the modeform_factory.
This beautifully obviates any need to construct a Form or deal with one. All done implicitly
There is some modest confusion easily in Django if model fields and form fields are not clearly differentiated, The hierarchy appears to be roughly as follows:
Models specify model fields. Model fields implement a formfield() method which supplies a Form Field.
The modelform_factory can create model forms and accepts dictionaries of form field classes and widgets as needed, and is quite flexible. But it's called implicitly in Generic views.
It strikes me this simple elegance could be conserved, and permit more flexible specification of form fields and/or widgets with a very small change to the code and associated docs.
I would propose that the default formfield() methods permit some more flexible configuration without having to subclass the model.Field: as suggested:
This would a very small change, starting with model.Field.__init__():
which would accept three new arguments, form_class=, choices_form_class= and widget=, defaulting to None, from which it can set self.form_class, self.choices_form_class and self.widget (precisely as it already does self.choices), and that the default formfield() method:
then use self.form_class, self.choices_form_class and self.widget if specified (not None)
Args of course overriding those.
This would mean form_class, choices_form_class and widget can be specified in the model definition and the Generic views can be enjoyed with implicit modelform_factory invocation in the background.
I'd be happy to whip up a PR for the code (and if it passes all tests submit), and take advice on where doc needs changing beyond the page cited above and perhaps:
https://docs.djangoproject.com/en/4.1/ref/models/fields/#field-api-reference
Regards,
Bernd.
No comments:
Post a Comment