django Javascript dropdown

耗尽温柔 提交于 2021-01-04 09:11:17

问题


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>

回答1:


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.

<html>
<head>
<script>
var json = {
    "Chevy": ["chev1", "chev2", "chev3"],
    "Dodge": ["dodge1", "dodge2", "dodge3"],
    "Ford": ["ford1", "ford2", "ford3"]
};

function carMake () {
    select = document.getElementById('slct1');
    select.options.length = 0;
    for(make in json) {
        select.options[select.options.length] = new Option(make, make);
    }
}

function carModel(sel) {
    var car_make = sel.options[sel.selectedIndex].value
    select = document.getElementById('slct2');
    select.options.length = 0;
    for(var i=0;i<json[car_make].length;i++) {
        select.options[select.options.length] = new Option(json[car_make][i], i);
    }
}
</script>
</head>

<body>
Choose Car Make:
<select id="slct1" onchange="carModel(this)"></select>
<script> carMake(); </script>

Choose Car Model:
<select id="slct2" name="slct2"></select>
</body>
</html>

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:

from <your-app>.models import Make
from <your-app>.models import Model
import json

json_dict = {}
for car_make in Make.objects.all():
    json_dict[car_make] = Model.objects.filter(make=car_make)
json_data = json.dumps(json_dict)

Then you take json_data and 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.




回答2:


You don't need javascript to do some fancy dropdown. You can use Django Forms to do it for you. All you need is to provide forms.py some information about the choices that a user can make and you will have your form rendered without you having to do anything more.

Look at my forms.py to see how I have done it.




回答3:


You should convert query set to list before using json.dumps otherwise it will give you an error which is "NOT JSON SERIALIZABLE"

from <your-app>.models import Make
from <your-app>.models import Model
import json

json_dict = {}
for car_make in Make.objects.all():
    json_dict[car_make] = list(Model.objects.filter(make=car_make).value())
json_data = json.dumps(json_dict)


来源:https://stackoverflow.com/questions/14763701/django-javascript-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!