I have the following code:
show_game = forms.ChoiceField(widget=forms.RadioSelect(attrs={
'class':'col-8',
}), choices=YES_NO_CHOICES,label='Show game?')
how can I get the label already set in the ModelForm field called show_game
? this is my custom template for a custom widget I’m using:
<div class="row mb-3">
<label class="col-md-4 control-label">{{widget.label}}</label>
</div>
I tried the code above and a bunch of variations but I still can’t get the label for the field . Note: I’m not getting the field from the YES_NO_CHOICES
. I was only able to fetch the label if I place it in widget.attrs.label
but it won’t make sense since I added a label already.
Let’s look at your field defintion:
CraftedPvP:
show_game = forms.ChoiceField(widget=forms.RadioSelect(attrs={
'class':'col-8',
}), choices=YES_NO_CHOICES,label='Show game?')
I’m going to reformat this to make it a little more clear:
show_game = forms.ChoiceField(
widget=forms.RadioSelect( attrs={'class':'col-8',} ),
choices=YES_NO_CHOICES,
label='Show game?'
)
By separating each parameter to it’s own line, you can more easily see that label
is an attribute on the field and not on the widget .
You should be able to reference the label as field.label
within the context of rendering the field.
1 Like
Hm. Still new. So I could understand that field.label
is to be used, as I’ve seen threads about it…
<label class="col-md-4 control-label">{{field.label}}</label>
I updated line 2 of the custom html for my widget like before. But, I still don’t see the label. If it helps, I declared the field in my .html page like so:
</div>
{{gameInfoForm.show_game}}
</fieldset>
What am I doing wrong?
It’s not visible nor available within the widget , because the label is not part of the widget. It’s part of the field.
For example, if I copy the HTML rendered for a simple field in a form, I see:
<div class="fieldWrapper">
<label for="id_name">Name:</label>
<input type="text" name="name" required="" id="id_name">
</div>
The widget renders the <input ...>
element. The rest of that is rendered by the field.
Hi! As per the Django documentation, it is possible to change/add HTML attributes of the widget in the Django forms.Form as follows:
class CommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["name"].widget.attrs.update({"class": "special"})
Is it possible to do this for the label, too?
Something like:
class CommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["name"].widget.attrs.update({"class": "special"})
self.fields["name"].label.attrs.update({"class": "special"})
Thank you!