在ajax调用中跳过Django默认字段validatio

时间:2017-10-13 10:54:56

标签: jquery ajax django forms validation

我浪费了很多时间,最后在这个伟大的论坛上寻求帮助。我有一个django启动器并且正在处理模型表单,该表单从用户获取地址详细信息并通过覆盖字段的清理方法进行验证。当我尝试使用ajax时,问题开始出现,其中ajax调用由于某种原因方便地跳过表单验证。请指导我,我无法弄清楚为什么我的视图中的is_valid()值为True,尽管view函数调用包含所有验证方法的AdrressForm对象。

// IN my views.py// 
@transaction.atomic
def update_profile_address(request):
    user = request.user
    if request.method == 'POST':
        address_form = AddressForm(request.POST, instance=user.profile)
        if address_form.is_valid():
            address_form.save()
            response_data = {"success_message": " Details Saved Successfully."}
            return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
            )
    else:
        address_form = AddressForm(instance=user.profile)
    return render(request, 'update_profile_address.html', {
        'address_form': address_form,
        })

//in my forms.py //
class AddressForm(forms.ModelForm): 
    class Meta: 
        model = Profile
        fields = ('address_city', 'address_state','address_country','address_pin')
        labels = { 
                    'address_city': 'City', 
                    'address_state':'State', 
                    'address_country': 'Country', 
                    'address_pin':'Pincode',
        }
        widgets = { 
            'address_city': forms.TextInput(
                attrs={ 'required': True, 'placeholder': 'your city'}
            ),
            'address_state': forms.TextInput(
                attrs={'required': True, 'placeholder': 'Madhya Pradesh'}
            ),
            'address_country': forms.TextInput(
                attrs={ 'required': True, 'placeholder': 'India'}
            ),
            'address_pin': forms.TextInput(
                attrs={ 'required': True, 'placeholder': 'your pin code'}
            ),
        }

        def clean_address_city(self): 
            address_city = self.cleaned_data['address_city']
            print(address_city)
            if not address_city.isalpha(): 
                raise  forms.ValidationError('Location can be alphabetic only.')
            return address_city

        def clean_address_state(self): 
            address_state = self.cleaned_data['address_state']
            if not address_state.isalpha(): 
                raise  forms.ValidationError('State can be alphabetic only.')
            return address_state

        def clean_address_country(self): 
            address_country = self.cleaned_data['address_country']
            if not address_country.isalpha(): 
                raise  forms.ValidationError('Country name can be alphabetic only.')
            return address_country

        def clean_address_pin(self): 
            address_pin = self.cleaned_data['address_pin']
            if not address_pin.isnumeric(): 
                raise  forms.ValidationError('Pin can be numeric only.')
            return address_pin

// ajax call //
    $("#tab2_2").click(function(event){
        event.preventDefault(); 
        $('li.active').removeClass('active');
        $(this).closest('li').addClass('active');
        var url = $(this).attr('href');
        $.ajax({
            url: url,
            success: function(data){ 
                document.getElementById("inner-content").innerHTML = data;
                 $('#address-form').submit(function(event){ 
                    event.preventDefault();
                    console.log('form submission prevented');
                    address_form_submit();

                })

            }

        });
    }); 

    function address_form_submit(){ 
        console.log($('#address-form').serialize());

        $.ajax({
                    url:"{% url 'update_profile_address' %}", 
                    type:"POST",
                    /*data : { address_city : $('#address_city').val(),
                            address_state: $('#address_state').val(),
                            address_country:$('#address_country').val(),
                            address_pin:$('#address_pin').val(),
                            csrfmiddlewaretoken : '{{ csrf_token }}'
                    }, */
                    dataType: "json",
                    data: $('#address-form').serialize(),
                    success: function(json){ 
                    console.log(json);
                    var msg_box = document.getElementById('message-box');
                    if (json.success_message) { 
                        msg_box.innerHTML = json.success_message;
                        $('#message-box').addClass("alert-success");


                    };


                    }
                })

    };

1 个答案:

答案 0 :(得分:0)

缩进问题。您的干净方法在Meta类中。