Changes between Version 1 and Version 3 of Ticket #29468


Ignore:
Timestamp:
Jun 5, 2018, 2:00:30 AM (7 years ago)
Author:
Carlton Gibson
Comment:

Hi @mullerivan,

The docs for Styling widget instances give three approaches. The one you'd like to avoid is just the first.

In your case, I guess I'd recommend the second approach, to adjust the widget attrs inline in the form definition:

class ProfileForm(forms.ModelForm):
    full_name = forms.CharField()
    
    full_name.widget.attrs.update({'class': 'Anyclass',})

    class Meta:
        model = Profile    

Given that multiple options already exist, adding yet another keyword argument is not going to be worth it on balance. (The benefit won't justify the extra API surface area.)

Also see the ModelForm docs on Overriding default fields. If it's API you really want in your project there's nothing to stop you creating a base form class or mixin the takes an additional extra_widget_attrs and sets that appropriately during __init__(), as a generalisation of the third strategy outlined in the Styling widget instances docs linked above.

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #29468

    • Property Resolutionwontfix
    • Property Status newclosed
    • Property Summary Form Field declaration:Improve Form Field declaration of widget `attrs`.
  • Ticket #29468 – Description

    v1 v3  
    11Hi guys, I want to  improve the way  of  declear  html attrs into a Fields With out  declaring the default widget again.
    22
     3Example:
     4
    35{{{
    4 example:
    56class ProfileForm(forms.ModelForm):
    67    class Meta:
    78        model = Profile
    8 full_name = forms.CharField(widget=forms.TextInput(attrs={'class': Anyclass',}))
     9   
     10    full_name = forms.CharField(widget=forms.TextInput(attrs={'class': Anyclass',}))
    911}}}
    1012
     13As Field documentaiton say into the init:
    1114
     15"""Each Field has a default Widget that it'll use if you don't specify this.  n most cases, the default widget is TextInput:"""
    1216
    13 As Field documentaiton say into the init:
    14 """Each Field has a default Widget that it'll use if you don't specify this.  n most cases, the default widget is TextInput:"""
    1517Woudl be  god to declare it  as
    1618
Back to Top