How to add a shortcut to a Django form

I am using a Django form for input. However, I would like to tweak it a bit. For example, the following Django code will translate to:

#Django code

aerial_size_dist = forms.ChoiceField(initial='Very Fine to Fine') 

#Translated HTML  
<tr><th><label for="id_aerial_size_dist">Aerial size dist:</label></th><td><select name="aerial_size_dist" id="id_aerial_size_dist"></select></td></tr>

My question is, how do I add a shortcut property, such as a “style”, from the work of Django? Can a widget change the label property of a Django form?

HTML Target

<tr><th><label for="id_aerial_size_dist" style="display:none;">Aerial size dist:</label></th><td><select name="aerial_size_dist" id="id_aerial_size_dist"></select></td></tr>
+3
source share
3 answers

A similar problem was answered here: Get the ID of the field widget in the form set . Although it does not allow you to directly configure the identifier, it uses the default identifier (auto-generated) ID

(short answer) use this in a template:

EDIT:

<label for="{{ form.my_field.id_for_label }}">{{ form.my_field.label }}</label>

: ( - . )

<label for="{{ form.my_field.auto_id }}">{{ form.my_field.label }}</label>
+5
class FormName(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(FormName, self).__init__(*args, **kwargs)
        self.fields['field_name'].widget.attrs['style'] = '...'
0

All Articles