0

I am using a django ModelForm and CreateView with AJAX form submission to allow a user to upload a file. Even after selecting a file, upon clicking submit, the field is set to blank and form fails validation claiming that no file has been selected.

I believe I have taken care of the normal culprits for this sort of behavior. I have set enctype="multipart/form-data" and method="post" in my form. ModelForm save method includes files, so I'm not sure why the uploaded file is not going through.

Here is the form html:

    <form id="application_form_id" method="post" action="{% url 'jobs:submit_application_form' job_pk=job.pk %}" enctype="multipart/form-data">
        {% csrf_token %}
        <div class="modal-header">
            <h5 class="modal-title" id="applicationModalLabel">Apply</h5>
            <button type="button" class="close" id="applicationClose" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div id="application_form_content" class="modal-body">
            {% include 'jobs/basic_form.html' %}
        </div>
        <div class="modal-footer">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>

And here is the CreateView:

class JobApplicationFormView(LoginRequiredMixin, generic.edit.CreateView):
    model = JobApplication
    user_model = User
    context_object_name = 'application'
    form_class = JobApplicationForm
    template_name = 'jobs/student/student_job_detail.html'
    success_url = reverse_lazy('jobs:student_job_detail')

    def form_invalid(self, form):
        response = super().form_invalid(form)
        if self.request.is_ajax():
            valid = False
            data = {
                'form': render_to_string('jobs/basic_form.html', request = self.request, context = {'form' : form}),
                'valid': valid,
            }
            return JsonResponse(data)
        else:
            return response

    def form_valid(self, form):
        form.instance.student_user = self.request.user
        form.instance.job = self.kwargs['job_pk']
        response = super().form_valid(form)
        if self.request.is_ajax():
            valid = True
            data = {
                'form': render_to_string('jobs/student/basic_form.html', request = self.request, context = {'form' : form}),
                'valid': valid
            }
            return JsonResponse(data)
        else:
            return response

And here is the AJAX call (although I think it's irrelevant since I'm getting the form html with errors back)

// Submit application form via AJAX
$(document).ready(function() {
    var $myForm = $('#application_form_id')
    var initial = $('#application_form_content').html()
    $('#applicationClose').on('click', function() {
        $('#application_form_content').html(initial)
    });
    $myForm.submit(function(event) {
        event.preventDefault()
        var $formData = $(this).serialize()
        $.ajax({
            type: $myForm.attr('method'),
            url: $myForm.attr('action'),
            data: $formData,
            success: handleFormSuccess,
            error: handleFormError,
            dataType: 'json',
        });

        function handleFormSuccess(data, textStatus, jqXHR){
            $('#application_form_content').html(data.form);
            if (data.valid) {
                initial = data.form
                $('##application_form_content').html(data.form)
                $('#applicationModal').modal('hide')
                console.log(valid)
            }
        };

        function handleFormError(jqXHR, textStatus, errorThrown){
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        };
    });
});
cmanbst
  • 179
  • 3
  • 13

1 Answers1

0

I found the issue. Serializing and submitting the form data as shown in the question does not include the file data from the form. I needed to create a new form data object and append the file manually.

Here is the formData documentation.

The below AJAX call seems to be working properly.

$(document).ready(function() {
    var $myForm = $('#application_form_id')
    var initial = $('#application_form_content').html()
    $('#applicationClose').on('click', function() {
        $('#application_form_content').html(initial)
    });
    $myForm.submit(function(event) {
        event.preventDefault()
        var data = new FormData($myForm.get(0));
        data.append('file', $('#id_cover_letter')[0].files)
        $.ajax({
            type: $myForm.attr('method'),
            url: $myForm.attr('action'),
            data: data,
            processData: false,
            contentType: false,
            success: handleFormSuccess,
            error: handleFormError,
            dataType: 'json',
        });

        function handleFormSuccess(data, textStatus, jqXHR){
            $('#application_form_content').html(data.form);
            if (data.valid) {
                initial = data.form
                $('#application_form_content').html(data.form)
                $('#applicationModal').modal('hide')
            }
        };

        function handleFormError(jqXHR, textStatus, errorThrown){
            console.log(jqXHR.responseText)
        };
    });
});
cmanbst
  • 179
  • 3
  • 13