我的django形式有两个下拉框,第一个下拉框包含汽车品牌(奥迪,宝马),第二个下拉框包含不同型号,例如奥迪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) {
}
});
});
答案 0 :(得分:0)
在您的情况下,它将包含整个页面的html代码。在这种情况下,您需要有一个API视图返回说JSON输出,而在ajax成功函数中,您使用您获得的JSON更新第二个下拉列表。还请考虑为此类任务尝试REST API。 如果你想使用你自己的api响应,你可以考虑这样的函数作为视图中的响应:
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。
您还可以考虑使用API网址,方法是定义" apipatterns"在urls.py