简体   繁体   中英

asynchronus form submission django

I'm using ajax to submit a form, and it's working. But it's not working asynchronously. When I'm trying to upload files it uploaded successfully and then the page loads again. I want it to make asynchronously. In addition, I want to make a progress bar too. But things not working as I expected.

my forms.py

from django import forms
from .models import Comment
from .models import post

class UploadForm(forms.ModelForm):
class Meta:
    model = post
    fields = ('image', 'video', 'content',)

my views.py

def django_image_and_file_upload_ajax(request):
if request.method == 'POST':
   form = UploadForm(request.POST, request.FILES)
   if form.is_valid():
       form.instance.author = request.user
       form.save()
       return JsonResponse({'error': False, 'message': 'Uploaded Successfully'})
   else:
       return JsonResponse({'error': True, 'errors': form.errors})
else:
    form = UploadForm()
    return render(request, 'blog/upload.html', {'form': form})

and my upload.html

{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<main>
    <div class="container">
      <div class="row">
        <div class="col-md-8 my-5">
            <div class="content-section" style="padding:10px 20px">

               <form
                enctype="multipart/form-data"
                id="id_ajax_upload_form" method="POST"
                novalidate="">
                    <fieldset class="form-group">
                    {% csrf_token %}
                        <legend class="border-bottom mb-4"><i class="fas fa-feather-alt text-muted mr-2"></i>Create a post</legend>
                        {{ form.as_p }}
                    </fieldset>
                    <div class="form-group">
                        <input type="submit" />
                    </div>
               </form>
            </div>
        </div>
      </div>
    </div>
</main>
{% endblock content %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
// form upload
 $('#id_ajax_upload_form').submit(function(e){
     e.preventDefault();
     $form = $(this)
     var formData = new FormData(this);
     $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        success: function (response) {
            $('.error').remove();
            console.log(response)
            if(response.error){
                $.each(response.errors, function(name, error){
                    error = '<small class="text-muted error">' + error + '</small>'
                    $form.find('[name=' + name + ']').after(error);
                })
            }
            else{
                alert(response.message)
                window.location = ""
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });
});
// end
where i get wrong?

Ok, Got it! But anyone know about how to add a progressbar will be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM