![](/img/trans.png)
[英]set drop down value of second box depending on selection of first drop down
[英]second drop down box is not updating depending on value selected in first drop down box django
我在django表單中有兩個下拉框,第一個下拉框包含汽車的品牌(audi,BMW),第二個下拉框包含不同的型號,例如audi A1。 我試圖根據用戶在第一個下拉框中選擇的內容來動態更新第二個下拉框。 我正在嘗試使用jquery和ajax來執行此操作,我遇到的問題是將kwargs傳遞給第二個下拉框。
視圖
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) {
}
});
});
就您而言,它將包含整個頁面的html代碼。 在這種情況下,您需要具有一個返回例如JSON輸出的API視圖,並在ajax成功函數中使用您獲得的JSON更新第二個下拉列表。 還請考慮針對此類任務嘗試使用REST API。 如果您想使用自己的api響應,則可以在視圖中考慮諸如response的功能:
def api_response(success, payload={}):
response = JsonResponse({
'status': 'success' if success else 'error',
'payload': payload
})
response.status_code = 200 if success else 400
response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
return response
而不是在ajax調用的成功函數中使用data.payload。
您可能還需要考慮通過在urls.py中定義“ apipatterns”來使用API URL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.