STEP#1: In models.py
class smsTemplate(models.Model):
sms_temp_id = models.IntegerField(default=False)
text_arabic = models.TextField(default=False)
text_english = models.TextField(default=False)
class Meta:
db_table='sms_template_db'
STEP#2: In view.py
def sms_page(request):
mess_tem = smsTemplate.objects.all()
data2 = serializers.serialize('json', mess_tem)
return render(request, "en/page.html" , {'data2':data2})
STEP#3: javaScripts
function display(){
var sel_lan1 = document.getElementById("lan1")
var sel_lan2 = document.getElementById("lan2")
var temp_ = '{{ data2 |escapejs }}';
if(sel_lan1.checked == true){
alert("test1")
document.write(temp_. text_arabic);
}else if(sel_lan2.checked == true){
alert("test2")
}else{
alert("no channel selecte it")
}
}
Can you guide me how to get data from model and then sent them to javascripts?
So it’s not clear what you’re trying to accomplish here. You need to provide more details about exactly what you want to have happen.
Keep in mind that Django runs on the server while the JavaScript is running in the browser. You need to identify when you want to make this data available.
Are you looking to include the data in the JavaScript code, such that when the template is rendered and sent to the browser, those values are already there? Or are you looking to have the JavaScript retrieve data from the server while it’s running in the browser?
Yes, that’s what I want it.
let me explain more, I created project that send sms. So, The user enter phone and click choice of the language. Based on language, It appears text template from DB in text area.
I’ve coded these in js if the user select english language, It take the data of text from models to js and post them to show in html.
if(sel_lan1.checked == true){
alert("test1")
// What write here to get data for English text
}else if(sel_lan2.checked == true){
alert("test2")
// What write here to get data for Arabic text
}else{
alert("not selected")
}
So yes, if this is constant data to be generated at the time the template is rendered, you will want to use the json_script tag to make the data available to the JavaScript code.