Multiple widgets for one form field in Django
I have the following form:
class ExcipientForm(ModelForm):
class Meta:
model = Excipient
fields = (
"Excipient_type",
"Excipient_concentration",
)
widgets = {
'Excipient_type': Select(attrs={
'style' : 'width:100%;',
'class' : 'dropdowns',
}),
'Excipient_concentration': TextInput(attrs={
'class': 'slider',
'type': 'number',
'value':"20",
'max':"100",
'step': "0.1",
'id':"excipient_concentration"
}
)
}
ExcipientFormSet = inlineformset_factory(
Parameters,
Excipient,
ExcipientForm,
can_delete=False,
min_num=1,
extra=0
)
This is the template to post to the form:
<form action="" id="form-container" method="POST"> {% csrf_token %} <div class='row'>
<div class='col'>
<label for="id_API_batch_number" class="form-label">API batch number : </label>
</div>
<div class='col'>
{{ parameter_form.API_batch_number }}
</div>
</div>
<hr class="my-4">
<div class='excipient-form'>
{{ excipient_form }}
{{excipient_form.id.auto_id}}
<input type="range" class="slider" name="slidervalue" value='20' max="100" step="0.1" onchange="updateTextInputRange(this.value);">
</div>
<button id="add-form" type="button">Add Excipient</button>
<hr class="my-4">
<label for="num6" class="form-label">Total Concentration: </label>
{{ parameter_form.Total_concentration }}
<br></br>
<input type="submit" id="submit" class="btn btn-primary" value="Submit">
</form>
I'm trying to get the sliders and it's corresponding number field to "sync".
This is the JS I have at the moment.
//Update Textbox value from slider value
function updateTextInputRange(val) {
document.getElementByID('excipient_concentration').value = val; // text input
//checkValueSum();
}
Some of the things I tried:
- Finding out the ID for each instance of the slider and number input. This failed as every instance has the same ID.
- Tried using multiple widgets in the same form. This failed the html element just took the properties of the final widget properties.
- Tried adding another field in the model and using that as a slider in the forms widget. This does not allow me to "sync" the slider and number values without making a call back to the server.
Any ideas on how this can be accomplished?
Django documentation. MultiWidget. In your Case:
widget = MultiWidget(widgets={'Excipient_type': Select, 'Excipient_concentration': TextInput})
But try to read documentation. More here: https://docs.djangoproject.com/en/4.1/ref/forms/widgets/#multiwidget