I have a Django form where the user can select a variable in a choice field, start date and end date in a select date widget. For different variables, the possible start and end dates varies. The form works, but only with one pre-defined date range for all variables. How can I change the possible start and end dates according to the variable?
from django import forms
from datetime import datetime
Parameter_CHOICES = [
('', 'Wähle ein Umweltvariable'),
('niederschlag', 'Niederschlag [L/m²]'),
('bodentemperatur_5cm', 'Bodentemperatur in 5cm Tiefe [°C]')
]
class DataForm(forms.Form):
parameter = forms.ChoiceField(
widget=forms.Select,
choices=Parameter_CHOICES)
start_date = forms.DateField(label='Beginn:', widget=forms.SelectDateWidget(years=list(range(2007,2023))))
end_date = forms.DateField(label='Ende:', initial=datetime.now, widget=forms.SelectDateWidget(years=list(range(2007,2023))))
What i need is to set the
years=list(range(2007,2023))
for niederschlag
and for bodentemperatur_5cm to
years=list(range(1991,2023))
Is it possible to do this in the forms.py or do I have to make this in javascript/html?
Update I try to solve it with jQuery, but I stuck. I try to change the Years Range choicec according to parameter with this function:
$("#id_parameter").on('change', function(){
var parameter = $("#id_parameter").val();
if (parameter == 'niederschlag') {
$("#id_start_date_year").val(2007);
}
if (parameter == 'bodentemperatur_5cm') {
$("#id_start_date_year").val(1991);
}
But this only change the value the user can see first. How can I change the possible years or range after the user select the parameter with jQuery?