【问题标题】:second drop down box is not updating depending on value selected in first drop down box django第二个下拉框不会根据第一个下拉框 django 中选择的值进行更新
【发布时间】:2017-03-12 16:05:30
【问题描述】:

我的 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) {

        }
      });
});

【问题讨论】:

    标签: jquery ajax django


    【解决方案1】:

    在您的情况下,它将包含整个页面的 html 代码。在这种情况下,您需要有一个返回 JSON 输出的 API 视图,并在 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 URL,通过在 urls.py 中定义“apipatterns”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 2012-01-04
      • 1970-01-01
      • 2018-09-29
      相关资源
      最近更新 更多