Загрузка изображения с использованием API fetch не работает в django - PullRequest
0 голосов
/ 03 апреля 2020

Мой файл views.py

def change_profile_picture(request):
    if not request.user.is_authenticated:
        return JsonResponse({"status": "403", "msg": "Unauthorized request"})
    if request.method == 'POST':
        if request.is_ajax():
            form = UploadPictureForm(request.POST)
            if form.is_valid():
                customuser = request.user.customuser
                customuser.picture = form.cleaned_data['picture']
                customuser.save()
                return JsonResponse(
                    {
                        "status": "200",
                        "msg": "Successful",
                        "data": f"{customuser.picture.url}"
                    }
                )
            else:
                return JsonResponse({"status": "400", "msg": "invalid form"})
        else:
            return JsonResponse({"status": "401", "msg": "Bad request"})
    else:
        return JsonResponse({"status": "403", "msg": "invalid request method"})

forms.py

class UploadPictureForm(forms.Form):
    picture = forms.ImageField(
        label="Profile picture"
    )

Javascript код:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$('.upload-btn').on('click', () => {
    document.getElementById('id_picture').click();
})
$('.close-btn').on('click', () => {
    document.getElementById('profile-picture').src = $('#profile-picture').data('target');
    document.getElementById('submit-picture').style.visibility = 'hidden';
})
$('#submit-picture').on('click', () => {
    var picture = document.querySelector('input[type="file"]');
    var formData = new FormData();
    formData.append('csrfmiddlewaretoken', getCookie('csrftoken'));
    formData.append('picture', picture.files[0]);
    fetch('/auth/change-profile-picture/', {
        method: 'POST',
        body: formData,
        cache: 'default',
        mode: 'cors',
        credentials: 'include',
        headers: {
            "X-Requested-With": "XMLHttpRequest",
        }
    })
    .then((res) => res.json())
    .then((data) => {
        if(data.status === '200') {
            document.getElementById('profile-picture').src = data.data;
            alert("done");
        } else {
            console.log(data.msg);
        }
    })
    .catch((err) => console.log(err))
})

HTML шаблон:

image

Функция просмотра change_profile_picture возвращает invalid form, и я не знаю почему. До сих пор я заметил, что файл изображения на самом деле не отправляется с API выборки. Я также попытался перейти от использования Javascript для отправки к использованию обычного тега формы HTML, он по-прежнему выдает ту же ошибку. Изменение унаследованного класса формы на ModelForm заполняет поле только значением по умолчанию. Как мне это исправить?

1 Ответ

0 голосов
/ 09 апреля 2020

Я обнаружил в представлении change_profile, где я инициализировал форму с отправленными данными, я не заполнил форму request.FILES, например:

<code>
 if request.method == 'POST':
        if request.is_ajax():
            form = UploadPictureForm(request.POST, request.FILES)
<more code>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...