use javascript variable in django template

django, django-templates, javascript, jquery

Solution

You didn't pass the value from javascript function to django template tag. But in this case you can use ajax calls.

http://www.tangowithdjango.com/book/chapters/ajax.html

https://bradmontgomery.net/blog/2008/11/24/a-simple-django-example-with-ajax/

Update:

See this you can understand what's going on.

How to pass javascript variable to django custom filter

Hope this is helpful idea.

Problem

I have a custom template tag that retrieves a list of countries over a web call to SOAP service and populates html select tag. Now I have another template tag that displays a list of choices for the given country and,obviously enough, it takes country name as an argument. So I can pass the country name to the second custom tag only after onchange event is triggered on html select tag and I have country name as a javascript variable chosen by user. How would I pass this value to the custom template tag? Here are my custom tags ``` from mezzanine import template from suds.client import Client register = template.Library() @register.as_tag def get_countries(*args): url = 'http://www.sendfromchina.com/shipfee/web_service?wsdl' client = Client(url) countries = client.service.getCountries() countries = map(lambda x: x._enName, countries) return countries @register.as_tag def get_available_carriers(weight,country,length,width,height): url = 'http://www.sendfromchina.com/shipfee/web_service?wsdl' client = Client(url) rates = client.service.getRates(weight,country,length,width,height) rates=map(lambda x: (x._shiptypecode, x._totalfee), rates) return rates ``` Here is my html select tag ``` <select id='countrylist' onchange="getOption(this)"> {% get_countries as countries %} {% for country in countries %} <option>{{ country }}</option> {% endfor %} <select> ``` And finally, here is my javascript ``` <script type="text/javascript"> function getOption(sel){ var country = sel.value; {% get_available_carriers 1 country 10 10 10 as carriers %} console.log('{{ carriers }}') } </script> ``` I can't seem to pass country js variable to `get_available_carriers` tag Any help is highly appreciated! Thanks

Original source

Related problems