Form Inheritance best Practice: Manipulating Fields of the Base Class

28 views
Skip to first unread message

sbrandt

unread,
Nov 5, 2012, 6:29:05 PM11/5/12
to django...@googlegroups.com
This is a very theoretical question about best practice. I and surely most other users know how to do this in any way, but I'm interested in the best solution, if it exists.

Given that:
  • I am inheriting a given form I cannot modify directly, let's say the AuthenticationForm
  • I want to to manipulate a field of this form, i.e. add a "placeholder" attribute to the username and password fields
  • I want to use the fields of the parent class because of DRY and maintainability

The solutins I saw until now somehow contain injecting the attribute in the __init__ method:

class MyAuthenticationForm(AuthenticationForm):

    def __init__(self, *args, **kwargs):

        ...

        self.fields['username'].widget.attrs['placeholder'] = 'username'

        ...


Since this is done every instantiation, I feel like this is a bit redundant. In fact, these operations are negligible and should not affect performance at all. This solution does seem to work as well:

class MyAuthenticationForm(AuthenticationForm):

    pass

MyAuthenticationForm.base_fields['username'].widget.attrs['placeholder'] = 'username'

...

It seems a bit dirty to change the class outside the class definition, but at least it is only called once and manipulates the class instead of the objects which seems on the other hand much more reasonable.

What do you think? Is there a hook that is only called once the class is created? Are there benefits or drawbacks?


Greets

Reply all
Reply to author
Forward
0 new messages