Django模型表单依赖修改

时间:2015-05-29 11:13:28

标签: jquery python ajax django forms

我有两个模式表单字段:actionservice

class InputsModelExtended(models.Model):
    service = models.CharField(max_length=1000, choices=SERVICE_CHOICES, blank=True)
    action = models.CharField(max_length=1000, choices=ACTION_CHOICES, blank=True)
    def __str__(self):      
        return self.input   
    class Meta:
       ordering = ["service"]
       unique_together = ('service', 'action')

我将它们传递给form.py并创建了模型表单:

class InputsModelExtendedForm(ModelForm):
class Meta:
    model = InputsModelExtended
    #fields = ['service', 'action', 'input']
    fields = '__all__'
    widgets = {'service': forms.fields.Select(attrs={'class': 'service_select_box'}), 'input': forms.fields.TextInput(attrs={'placeholder': 'Enter an input', 'class': 'selectpicker'}), 'object': forms.fields.TextInput(attrs={'placeholder': 'Enter an object', 'class': 'selectpicker'})}

然后我在更改第一个字段时收到ajax post请求:

$(document).ready(function() {
    var select_box = $('.service_select_box')
    select_box.on('change', function(e) {
        console.log('event ', select_box.val());
        data = { "csrfmiddlewaretoken": '{{ csrf_token }}', 'action': select_box.val()};
        $.ajax({
            url: "/ajaxrequest",
            type: "POST",
            data: data,
            success: function (data) {console.log('success', data);},
            error: function (data) {console.log('error', data);},
        });
    });
    return false;
});

现在我应该如何将action字段变体调整为service中选择的选项?我尝试通过ajax_text将其发布到模板:

def ajax_test(request):
choices = {'assistant app' : (('ask' : (('Choose action', 'Choose action',), ('ask.friends','ask.friends',)),
'wisdom' : (('Choose action', 'Choose action',), ('wisdom.wisdom', 'wisdom.wisdom'))}
if request.is_ajax() and request.POST['action']:
    action = request.POST['action']
    #message = "ur action is " + str(request.POST['action'])
    action_choices = choices[action.lower()]
else:
    message = "empty or not an ajax"
form = InputsModelExtendedForm(request.POST or None, action_choices=action_choices) #passing form to template
InputsAll = InputsModelExtended.objects.all() #passing all objects to template
return render(request, 'inputs_forms_css.html', {'form': form, 'InputsAll': InputsAll, 'id': id})

但是action字段似乎没有刷新而改变,虽然通过ajax成功响应我得到正常的修改选择:

Service: <select class="service_select_box" id="id_service" name="service">
<option value="" selected="selected">---------</option>
<option value="Apps">Ask</option>
Action: <select id="id_action" name="action">
<option value="Choose action">Choose action</option>
<option value="ask.friends">ask.friends</option>

第二个字段选择集是应该通过jquery修改还是可以用另一种方式完成? Thx提前。

1 个答案:

答案 0 :(得分:0)

首先,您需要在模板级别迭代第二个字段的选项,以添加您要过滤的任何属性。在此示例中,我们将按第一个选择的值过滤第二个选项。

var firstSelect = $('#id_first_select'),
    secondSelectOptions = $('#id_second_select option');

firstSelect.on('change', function(e) {
    var value = $(this).val();

    secondSelectOptions.hide();
    secondSelectOptions.filter('[data-related-value="' + value + '"]').show();
});