0

I have a django form which contains, among other things, two fields for choosing climate parameters. Both of these fields are populated by the same CHOICES, but I needed the scond one to be influenced by what was selected in the first. Basically if a parameter is selected in the first then it should by removed from the choices in the second.

I now have code which works very well for this except for one problem. I need the fields to be language aware.

forms.py

class ClimateForm(forms.Form):
    ...
    param1 = forms.ChoiceField(choices=PARAM_CHOICES, label=_('Y axis one'), initial=_('Not Specified'),
                widget=forms.Select(attrs={"onChange":'activateParam()'}),
                )
    param2 = forms.ChoiceField(choices=PARAM_CHOICES, label=_('Y axis two'), initial=_('Not Specified'),
                required = False,
                )
    ...

I then call the activateParam() function which does this:

filter_form.js:

function activateParam() {
    // get value to exclude from select
    var param1Val = document.getElementById("id_param1").value;
    // get next element id
    var param2 = document.getElementById("id_param2");
    // param2.setAttribute("style", "display:block");
    updateSelect($('select[name=param2]'), param1Val);   
 }


function updateSelect(select, value) {
    // find and remove existing options
    select.find('option').remove();
    // loop through results and append to select as options
    for (var k in climate_params) {
        if (k!=value) {
            select.append($('<option value="'+k+'">'+climate_params[k]+'</option>'));
        }
    }
} 

climate_params is just an array of values and strings to populate the second field:

var climate_params = {
    '': 'Not Specified',
    'mean_air_temp': 'Mean Air Temperature', 
    'min_air_temp': 'Min Air Temperature', 
    'max_air_temp': 'Max Air Temperature',
    'sea_temp': 'Sea Surface Temperature',
    'mean_rel_hum': 'Mean Relative Humidity',
    'precipitation': 'Preciptitation',
};

So, I could modify this array or include another, but I need to know how to pass the language state to this JS script. Is there some way I can access the language variable directly in the JS?

Any help much appreciated.

Darwin Tech
  • 18,449
  • 38
  • 112
  • 187

1 Answers1

0

You could mark translation string in js directly,
or initialize the climate_params w/ Python translation object:

{# in template #}
var climate_params = {
    {% for param, label in PARAM_CHOICES %}
    '{{ param|escapejs }}: '{{ label|escapejs }}',
    {% endfor %}
};

Also have a look at Check How i get the current language in django?. If you're passing labels by Ajax, the translation is already done.

Community
  • 1
  • 1
okm
  • 23,575
  • 5
  • 83
  • 90