Django动态表单验证

时间:2016-10-29 00:28:54

标签: django django-models django-forms django-views django-validation

所以我是Django的新手,我创建了一个动态使用总共8个表单的View。有一个基本表单始终显示,然后只有当用户从下拉列表中选择该选项时才会显示另外7个表单(下拉列表位于HTML模板中)。

我现在正在尝试验证表单字段,当我静态显示所有8个表单时,每个表单的验证(清理方法)都能完美运行!但是,当我将其更改为根据用户选择动态显示表单时,基本表单的验证每次都会失败。

知道为什么会这样吗?如果有帮助,我可以提供表格/视图的实例!

模板:

<form0 id="BaseForm" action="/test_created/" method="post">
    {% csrf_token %}
    {{create_test_form.as_ul}} <br><br>
</form0>

<form1 id="vc1Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc1_form.as_ul}} <br><br>
</form1>

<form2 id="vc2Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc2_form.as_ul}} <br><br>
</form2>


<form3 id="vc3Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc3_form.as_ul}} <br><br>
</form3>


<form4 id="vc4Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc4_form.as_ul}} <br><br>
</form4>



<form5 id="vc5Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc5_form.as_ul}} <br><br>
</form5>


<form6 id="vc6Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc6_form.as_ul}} <br><br>
</form6>


<form7 id="vc7Form" action="" method="post" style="display:none">
    {% csrf_token %}
    {{vc7_form.as_ul}} <br><br>
</form7>


<div>
    <select id="validation_classes_id" name="all_validation_classes" onchange="showForm()">
        <option value="%">Choose the validation class</option>
        {% for val_class in all_validation_classes %}
         <option value="{{ val_class.id }}">{{ val_class.id}}  {{val_class.name }}</option>
        {% endfor %}
    </select> <br> <br>
    <form id="submit" action="" method="post">
        {% csrf_token %}
        <input type="submit" value="Submit" onclick=""/>
    </form>

</div>

<br><br>

<script>
    function showForm(){
        if (validation_classes_id.value == 1){
            console.log("Chose validation class 1");
            var div = document.getElementById('vc1Form');
            console.log(div)
            div.style.display='block';
        }
        else if (validation_classes_id.value == 2){
            console.log("Chose validation class 2");
            var div = document.getElementById('vc2Form');
            console.log(div)
            div.style.display='block';
        }
        else if (validation_classes_id.value == 3){
            console.log("Chose validation class 3");
            var div = document.getElementById('vc3Form');
            console.log(div)
            div.style.display='block';
        }
        else if (validation_classes_id.value == 4){
            console.log("Chose validation class 4");
            var div = document.getElementById('vc4Form');
            console.log(div)
            div.style.display='block';
        }
        else if (validation_classes_id.value == 5){
            console.log("Chose validation class 5");
            var div = document.getElementById('vc5Form');
            console.log(div)
            div.style.display='block';
        }
        else if (validation_classes_id.value == 6){
            console.log("Chose validation class 6");
            var div = document.getElementById('vc6Form');
            console.log(div)
            div.style.display='block';
        }
        else if (validation_classes_id.value == 7){
            console.log("Chose validation class 7");
            var div = document.getElementById('vc7Form');
            console.log(div)
            div.style.display='block';
        }
    }
</script>

查看:

def create_test(request):
    context = {
        'all_validation_classes': ValidationClass.objects.all(),
        'create_test_form': CreateTestForm,
        'vc1_form': VC1Form,
        'vc2_form': VC2Form,
        'vc3_form': VC3Form,
        'vc4_form': VC4Form,
        'vc5_form': VC5Form,
        'vc6_form': VC6Form,
        'vc7_form': VC7Form
    }
    if request.method == 'POST':
        create_test_form = CreateTestForm(request.POST)
        vc1_form = VC1Form(request.POST)
        vc2_form = VC2Form(request.POST)
        vc3_form = VC3Form(request.POST)
        vc4_form = VC4Form(request.POST)
        vc5_form = VC5Form(request.POST)
        vc6_form = VC6Form(request.POST)
        vc7_form = VC7Form(request.POST)

        if create_test_form.is_valid():

            print("This is where I am")
            print("Create Test form looks valid")
            vc_list = request.POST.getlist('validation_class', None)
            selected_vc = ValidationClass.objects.filter(pk__in=vc_list)
            global_val_class = selected_vc
            if vc1_form.is_valid():
                print("VC1Form is valid")
            else:
                print("Failing at VC1")
                return HttpResponseRedirect('/test_not_created/')
            if vc2_form.is_valid():
                print("VC2Form is valid")
            else:
                print("Failing at VC2")
                return HttpResponseRedirect('/test_not_created/')
            if vc3_form.is_valid():
                print("VC3Form is valid")
            else:
                print("Failing at VC3")
                return HttpResponseRedirect('/test_not_created/')
            if vc4_form.is_valid():
                print("VC4Form is valid")
            else:
                print("Failing at VC4")
                return HttpResponseRedirect('/test_not_created/')
            if vc5_form.is_valid():
                print("VC5Form is valid")
            else:
                print("Failing at VC5")
                return HttpResponseRedirect('/test_not_created/')
            if vc6_form.is_valid():
                print("VC6Form is valid")
            else:
                print("Failing at VC6")
                return HttpResponseRedirect('/test_not_created/')
            if vc7_form.is_valid():
                print("VC7Form is valid")
            else:
                print("Failing at VC7")
                return HttpResponseRedirect('/test_not_created/')
            return HttpResponseRedirect('/test_created/')
        else:
            print("Failing at create_test")
            return HttpResponseRedirect('/test_not_created/')
    else:
        create_test_form = CreateTestForm()
        vc1_form = VC1Form()
        vc2_form = VC2Form()
        vc3_form = VC3Form()
        vc4_form = VC4Form()
        vc5_form = VC5Form()
        vc6_form = VC6Form()
        vc7_form = VC7Form()
        return render (request, 'create_test.html', context)

形式:

class CreateTestForm(forms.ModelForm):
    class Meta:
        model = Test
        fields = ['name', 'test_group', 'description', 'query_text', 'failure_condition', 'status']


    def clean_status(self):
        print("This is where I am")
        print(self.cleaned_data)

    def getKey(self):
        return "create_test_form"

class VC1Form(forms.Form):
    expected_relation = forms.ChoiceField(choices = [('<','<'), ('>','>'), ('=','='), ('<=','<='), ('>=','>='), ('!=','!=')], required = True, label = 'Expected Relation: ')
    num_rows = forms.IntegerField(initial = 0)

    def getKey(self):
        return "vc1_form"

class VC2Form(forms.Form):
    expected_relation = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation: ')
    comparing_value_type = forms.ChoiceField(choices=[('Integer', 'Integer'), ('String', 'String')], required=True, label='Comparing Value Type')
    comparing_value = forms.CharField(initial = 0)

    def clean_comparing_value(self):
        exp_rel = self.cleaned_data['expected_relation']
        input_val_type = self.cleaned_data['comparing_value_type']
        input_val = self.cleaned_data['comparing_value']
        if (input_val_type == 'Integer'):
            print("I am in integer")
            try:
                int(input_val)
                print(int(input_val))
                return input_val
            except ValueError:
                print("Getting a value error")
                raise forms.ValidationError('Should be an Integer')
        elif (input_val_type == 'String'):
            print("I am in string")
            if (exp_rel != '!=' and exp_rel != '='):
                print("I am in here...")
                raise forms.ValidationError('Must have either = or != as comparator for String')
            try:
                int(input_val)
                print(int(input_val))
                print("getting a value error")
                raise forms.ValidationError('Should be a string')
            except ValueError:
                print("No value error")
                return input_val

    def getKey(self):
        return "vc2_form"


class VC3Form(forms.Form):
    comparing_value_2 = forms.CharField(label = 'Comparing Value', initial=" ")     #Need to figure out if its needed to make this into an array?
    # Not sure for now if there is a need to validate this data
    def getKey(self):
        return "vc3_form"

class VC4Form(forms.Form):
    # # This is mostly not needed as we will only check the values in the first column of the query results (as per documentation)
    wanted_value = forms.CharField(label = 'Name of corresponding column', initial=" ")        #Need to figure out how the input will be an actual variable from the select query
    acceptable_error_rate = forms.IntegerField(min_value = 0, max_value = 100, initial=0)
    def getKey(self):
        return "vc4_form"

class VC5Form(forms.Form):
    expected_relation_2 = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True,label='Expected Relation: ')
    comparing_value_type_2 = forms.ChoiceField(choices=[('Integer', 'Integer'), ('String', 'String')], required=True, label='Comparing Value Type')

    def clean_comparing_value_type_2(self):
        expected_relation_choices = ('<', '>', '=', '<=', '>=', '!=')
        exp_rel = self.cleaned_data['expected_relation_2']
        input_val_type = self.cleaned_data['comparing_value_type_2']
        print("This is the input val type")
        print(input_val_type)
        if (input_val_type == 'String'):
            print("I get in here")
            if (exp_rel != '=' and exp_rel != '!='):
                raise forms.ValidationError('Must have either = or != as comparator for String')
        return exp_rel

    def getKey(self):
        return "vc5_form"

class VC6Form(forms.Form):
    expected_relation_3 = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation: ')
    def getKey(self):
        return "vc6_form"

class VC7Form(forms.Form):
    expected_relation_one = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation to First Value: ')
    comparing_value_one = forms.IntegerField(label = 'First comparing value', initial=0)
    expected_relation_two = forms.ChoiceField(choices=[('<', '<'), ('>', '>'), ('=', '='), ('<=', '<='), ('>=', '>='), ('!=', '!=')], required=True, label='Expected Relation to Second Value: ')
    comparing_value_two = forms.IntegerField(label = 'Second comparing value', initial=0)
    def getKey(self):
        return "vc7_form"

0 个答案:

没有答案