Opened 10 years ago

Closed 10 years ago

#24295 closed New feature (fixed)

Allow specifying form field types in a ModelForm's Meta

Reported by: Loic Bistuer Owned by: Loic Bistuer
Component: Forms Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

It's currently very fiddly to use a custom form field together with ModelForm.

You can either set the field declaratively, which requires redefining all the attributes that would be automatically pulled from the model. It is not very DRY and quite error-prone, especially when it comes to required / blank. Or you can abuse models.Field.formfield by doing: my_field = MyModel._meta.get_field('my_field').formfield(form_class=MyCustomField).

This ticket proposes allowing:

class ArticleForm(ModelForm):
    class Meta:
        model = Article
        fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
        field_classes = {
            'slug': MySlugFormField,
        }

Change History (4)

comment:1 by Loic Bistuer, 10 years ago

Has patch: set
Owner: changed from nobody to Loic Bistuer
Status: newassigned

comment:2 by Carl Meyer, 10 years ago

Triage Stage: UnreviewedAccepted

I think this is worth doing. It addresses a common need for which the existing solutions are all either ugly or error-prone.

comment:3 by Tim Graham, 10 years ago

Triage Stage: AcceptedReady for checkin

comment:4 by Loic Bistuer <loic.bistuer@…>, 10 years ago

Resolution: fixed
Status: assignedclosed

In 00a889167f6699d02cee50848750d8d0e110d41c:

Fixed #24295 -- Allowed ModelForm meta to specify form field classes.

Thanks Carl Meyer and Markus Holtermann for the reviews.

Note: See TracTickets for help on using tickets.
Back to Top