Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add label ID in Django form

I am using Django form for inputs. However, I would like to custom it a little bit. For example the following Django code will be translated into:

#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 that how to add a label property such as "style" from working from the Django side? Can widget change Django form label property?

Target HTML

<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>
like image 649
TTT Avatar asked Nov 16 '25 01:11

TTT


1 Answers

Similar problem is answered here: Get the ID of a field widget in a formset . Although it doesn't allow you to customize the ID directly, it uses default (autogenerated) ID

(Short answer) use this in template:

EDIT:

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

old one: (this was not working in some cases - see comments)

<label for="{{ form.my_field.auto_id }}">{{ form.my_field.label }}</label>
like image 106
darkless Avatar answered Nov 17 '25 15:11

darkless



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!