我是 Python 和 Javascript 编程的新手,我已经学习 Python 几个月了,我很喜欢它。我一直在玩 django,这很酷我想知道如何使这个模型与 Iavascript 一起工作。我希望有人尽可能多地解释所涉及的代码,就像我要全面了解从 django 到 Javascript 的过程一样。
我想动态地是CarModel.objects.filter(make ='somename')
或只是'somename'。
这是一个正在使用的测试模型,因为它类似于我用于在线教程 (YouTube) 的 Javascript,脚本也如下所示:
class Make(models.Model):
name = models.CharField(max_length=50,blank=True,null = True)
#so so so so
class CarModel(models.Model):
name = models.CharField(max_length=50,blank=True,null = True)
make = models.ForeignKey(Make,blank=True,null = True)
现在,您将如何将这样的内容传递给您的 Javascript?
class Model(ModelForm):
make = forms.ModelChoiceField(queryset= Model.objects.none(), required=True)
def __init__(self, somemake,*args, **kwargs):
super(Model, self).__init__(*args, **kwargs)
self.fields['property'].queryset = Model.objects.filter(make = somemake)
class Meta:
model = Model
exclude= ('make')
<script type="text/javascript">
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "Chevy"){var optionArray = ["|","camaro|Camaro","corvette|Corvette","impala|Impala"];
}
else if(s1.value == "Dodge"){
var optionArray = ["|","avenger|Avenger","challenger|Challenger","charger|Charger"];
} else if(s1.value == "Ford"){
var optionArray = ["|","mustang|Mustang","shelby|Shelby"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
和这里的html
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
Choose Car Model:
<select id="slct2" name="slct2"></select>