W
W
Wondermarin2019-11-03 19:12:48
Django
Wondermarin, 2019-11-03 19:12:48

Sending AJAX + Django files?

Hello, I have a problem.
There is a form:

<form id="avatarUpload" action="{% url 'Home:Edit' %}" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="{{ form.avatar.name }}" id="{{ form.avatar.name }}">
</form>

Outside the form, there is a button that, when clicked, should trigger an AJAX request:
$('.action__button.primary').on('click', function() {
    $('#avatarUpload').submit(function() {
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function() {
                console.log('OK')
            }
        })
    })
})

But nothing happens.

views.py:
if request.method == 'POST':
        user_form = UserEditForm(data=request.POST, instance=request.user)
        form = ProfileEditForm(data=request.POST, files=request.FILES, instance=request.user.profile)
        if form.is_valid and user_form.is_valid:
            user_form.save()
            form.save()
            return redirect('Home:Edit')
        if request.is_ajax:
            form.save()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2019-11-03
@Wondermarin

Why doesn't the code for sending a file via AJAX work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question