表格无效:Django

时间:2019-01-31 17:21:11

标签: ajax django forms

我正在尝试通过ajax进行图像上载功能。我已经检查了所有内容,但Django仍将form.is_valid()返回为False,我仍然无法找出任何可能的错误。 form.is_valid()返回False。 在这里,我分享了views.py和html以及ajax代码

def upload_profile_picture(request):
data={}
uploadform=update_profile_photo(request.POST,request.FILES)
if uploadform.is_valid():
    image=request.FILES['profile_picture']
    if image:
        userID=request.POST['vuserID']
        usr=User.objects.get(pk=userID)
        if usr.id == request.user.id:
            usr.profile.profile_picture=image
            usr.profile.save()
            data['success']=True
        else:
            data['error_message']='you are not an authorized user'
            print('you are not an authorized user for uploading this photo')
    else:
        data['error_message']='image not supplied'
        print('image is not supplied in the form')
else:
    data['error_message']='profile photo upload form is not valid'
    print('this form is not valid')
return JsonResponse(data)

这是我的Ajax代码,它将表单数据发送到views.py 这是ajax代码:

<script>
$(document).ready(function () {
    $('#upload_profile_picture').submit(function (e) {
        e.preventDefault();
        alert(" i am uploading profile_picture");
        var form = $(this);
        var formData = new FormData(this);
        var user_id=$(this).attr('data-user-id');
        //var postDescription = $('#post-form-description').val().trim();
        var image = $('.upload_profile_photo').val().trim();
        //console.log(postDescription);
        console.log(image);
        if(!image){
            alert('cannot submit empty forms!');
            return false;
        }
        $.ajax({
            type: 'POST',
            url: "{% url 'account:upload_profile_picture' %}",
            data: formData ,

            success: function (data) {
                if(data.success){
                location.reload();
                }
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

以下是html文件的代码段:- profile.html

form method='post' action='' id="upload_profile_picture" enctype="multipart/form-data">
                                      Select file : input type='file' name='profile_picture' id='fileo' class='form-control upload_profile_photo' />
input type="hidden" name="csrfmiddlewaretoken" value="{{csrf_token}}" /> input type="hidden" name="vuserID" value="{{vuser.id}}" /> input type='submit' data-user-id="{{vuser.id}}" class='btn btn-info' value='Upload' id='upload' style="background-color: rgb(244,107,61);margin-left: 20vw;"> /form>

0 个答案:

没有答案