私は私のジャンゴ形式で2つのドロップダウンボックスを持っています。最初のドロップダウンボックスには車(audi、BMW)ダウンボックスにはさまざまなモデルが含まれています(例:audi A1)。ユーザーが最初のドロップダウンボックスで選択した内容に応じて、2番目のドロップダウンボックスを動的に更新しようとしています。私はこれを行うためにjqueryとajaxを使用しようとしています。問題は、私の2番目のドロップダウンボックスにkwargsを渡すことです。2番目のドロップダウンボックスは、最初のドロップダウンボックスで選択された値に応じて更新されませんdjango
図
def chose_car_make_model(request):
if 'car' in request.GET:
car_id = request.GET['car']
car_model_id = CarModel.objects.filter(id=car_id)
form = ChoseCarMakeModelForm(request.POST,ids=car_model_ids)
return render(
request,
template_name = 'form.html',
dictionary = {
'form':form,
}
)
else:
if request.method == "POST":
form = ChoseCarMakeModelForm(request.POST)
if form.is_valid():
car_model = form.cleaned_data['car_model']
car_make = form.cleaned_data['car_make']
car = CarOwner(
car_model = car_model,
car_make = car_make
owner = request.User
)
# Go to the next form in the process.
return redirect('view_car')
#return render(request, 'riskregister/menus/riskregister_index.html')
# Initial form
else:
form = ChoseCarMakeModelForm()
return render(
request,
template_name = 'form.html',
dictionary = {
'form':form,
}
)
forms.py
class ChoseCarMakeModelForm(forms.Form):
car_makes = forms.ModelChoiceField(
queryset=CarMake.objects.all().order_by('name'),
label = "Make:",
widget = Select(attrs={'class': 'span6 small-margin-top small-margin-bottom'}),
empty_label = "Select a make of car",
required=True
)
car_model = forms.ModelChoiceField(
queryset=CarModel.objects.all(makes=car_model_ids).order_by('name'),
label = "Model:",
widget = Select(attrs={'class': 'span6 small-margin-top small-margin-bottom'}),
empty_label = "Select a model of car",
required=True
)
def __init__(self, car_model_ids, *args, **kwargs):
super(ChoseCarMakeModelForm, self).__init__(*args, **kwargs)
# set the user_id as an attribute of the form
self.car_model_ids = car_model_ids
モデル
class CarMake(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
class CarModel(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
price = models.IntegerField()
make = models.ForignKey('CarMake')
jqueryの
$("#car_make").change(function(){
var make_id = $(this).val()
$.ajax({
url: "{% url chose_car_make_model %}",
data: {
car:make_id
},
success: function (data) {
}
});
});