Am new to programming in Python and Javascript and I have been learning Python for few months now and love it. I have been playing with django which is cool I was wondering how I can make this model work with a Iavascript. I’ll like someone to explain as much as the code involved as I just what to have a full understanding of the process from django to Javascript.
I want to dynamically is CarModel.objects.filter(make ='somename') or just ‘somename’.
This is a test model am using since its similar to the Javascript I use for tutorial from online (YouTube) the scripts is below as well:
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)
Now how will you pass say something like this to your 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>
and html here
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>
If you want to do in JS, this is how I would solve the problem.
First create a template that contains the following for the 2 select lists.
The above JS will read in the JSON object and update the Car Make when ever the dynamically populated Car Model select field is changed.
To generate the JSON object using your supplied Model you need to do the following:
In the view.py file:
Then you take
json_dataand and add that to your response render context.Finally alter the above template so that the JS variable json will be rendered to contain the JSON object passed from the view to the template.