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

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/qEU0jMe7TX8J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to