Submit form (django-form) with Imagefield via Jquery/Ajax Post?

后端 未结 2 408
攒了一身酷
攒了一身酷 2020-12-22 06:12

Im having some problems submitting a form (Django-form) with a imagefield with Jquery/ajax POST. Im getting back \"Field required\" validation errors on the imagefield..

相关标签:
2条回答
  • 2020-12-22 07:00

    There's a known issue with file uploads through jQuery ajax. There are tons of solutions and plugins out there, most of them using an iframe. However, I think the malsup jQuery form plugin provides the easiest of them all, with only a slight modification to your code:

    add this inside <head> tag:

    <script src="http://malsup.github.com/jquery.form.js"></script> 
    

    change the code within the Send function like so:

    buttons: {
        Send: function() { 
            $('.off').remove();
            var dialog = $(this),
                options = {
                    url: 'upload/',
                    type: 'POST',
                    success: function(response) {
                        // everything the same in here
                        }
                    };
    
            $('#myform').ajaxSubmit(options);
    
        }
      }
    

    Of course, on the server-side you need to make sure to follow the instructions from the documentation on how to bind the files to your form. For the most basic usage, it generally boils down to this:

    form = UploadForm(request.POST, request.FILES)
    

    p.s. one final note - as mentioned, it's a known issue, and the solution from malsup uses something called XMLHttpRequest Level 2. It's simply a newer API which provides more functionality to AJAX requests like file uploads, transfer progress information and the ability to send form data. My point being, older browsers don't support it, so bare in mind that if you want legacy-browser-users to make use of your site, you'll need to find an alternative.

    0 讨论(0)
  • 2020-12-22 07:03

    Sounds like you've a required attribute on the image field and you're not stopping default behaviour for click function.

    $('#imageupload').on('click', function(e) { 
        e.preventDefault();
    

    Bit hard to tell without your HTML code... You should ideally use a form with an id then target that element to bind to the 'submit' event so Enter key and touch events are also handled by the same code.

    $('#imageform').on('submit', function (e){ e.preventDefault() // other code here } 
    

    See also: Ajax Upload image

    0 讨论(0)
提交回复
热议问题