首先,我将system.id引入到JavaScrip中,这是一个唯一的整数,这没有任何问题。 但是,当我尝试将system.system_type变量(即Django CharField)引入到我的JavaScript中时,出现错误:Django Uncaught ReferenceError:未定义flat_plate。
(简化的)系统模型定义如下:
class System(models.Model):
system_name = models.CharField(default='default_name', max_length=200)
system_type = models.CharField(default='flat_plate', max_length=50, choices = SYSTEM_TYPE_CHOICES)
此处SYSTEM_TYPE_CHOICES定义为:
SYSTEM_TYPE_CHOICES = (
('flat_plate', 'flat_plate'),
('helical_coil', 'helical_coil')
)
我尝试运行的带有JavaScript的简化Django模板定义如下:
{% extends 'base.html' %}
<script>
{% block jquery %}
{% autoescape off %}
system_id = {{ system.id }} // runs without a problem
system_type = {{ system.system_type }} // Gives an error
{% endautoescape %}
console.log("system_id is: "+system_id)
console.log("system_type is: "+system_type)
{% endblock %}
</script>
{% block content %}
<p>{{system.system_type}} gives either "flat_plate" or "helical_coil"</p>
{% endblock %}
答案 0 :(得分:1)
在您的JavaScript中,因为它是一个字符串,所以需要使用引号:
system_type = '{{ system.system_type }}';