Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6352539
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T22:13:30+00:00 2026-05-24T22:13:30+00:00

I am trying to replicate the example given by Alex Kuhl on his excellent

  • 0

I am trying to replicate the example given by Alex Kuhl on his excellent post: http://kuhlit.blogspot.com/2011/04/ajax-file-uploads-and-csrf-in-django-13.html

However, I am not too successful in replicating this.

####### upload_page.html  

{% extends "base.html" %}
{% load i18n %}
{% block title %}Blog Post: Upload Files.{% endblock %}

{% block content %} 
<div id="maintext"> 
<p>To upload a file, click on the button below.</p>
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
<script>
    function createUploader(){
    var uploader = new qq.FileUploader( {
        action: "{% url ajax_upload %}",
        element: $('#file-uploader')[0],
        multiple: false,
        onComplete: function( id, fileName, responseJSON ) {
          if( responseJSON.success )
        alert( "success!" ) ;
          else
        alert( "Sorry, your upload has failed! Please contact us by telephone or email." ) ;
        },
        onAllComplete: function( uploads ) {
          // uploads is an array of maps
          // the maps look like this: { file: FileObject, response: JSONServerResponse }
          alert( "All complete!" ) ;
        },
        params: {
          'csrf_token': '{{ csrf_token }}',
          'csrf_name': 'csrfmiddlewaretoken',
          'csrf_xname': 'X-CSRFToken',
        },
      } ) ;
    }

    // in your app create uploader as soon as the DOM is ready
    // don't wait for the window to load
    window.onload = createUploader;
</script>
</div>
{% endblock %}

The views.py is as follows:

############### views.py
def upload_page( request ):
    ctx = RequestContext( request, {
        'csrf_token': get_token( request ),
    })
    return render_to_response( 'success/upload_page.html', ctx )

def save_upload( uploaded, filename, raw_data ):
    filename = settings.UPLOAD_STORAGE_DIR
    '''
    raw_data: if True, uploaded is an HttpRequest object with the file being
        the raw post data
        if False, uploaded has been submitted via the basic form
        submission and is a regular Django UploadedFile in request.FILES
    '''
    try:
        from io import FileIO, BufferedWriter
        with BufferedWriter( FileIO( filename, "wb" ) ) as dest:
            # if the "advanced" upload, read directly from the HTTP request
            # with the Django 1.3 functionality
            if raw_data:
                foo = uploaded.read( 1024 )
                while foo:
                    dest.write( foo )
                    foo = uploaded.read( 1024 )
            # if not raw, it was a form upload so read in the normal Django chunks fashion
            else:
                for c in uploaded.chunks( ):
                    dest.write( c )
            # got through saving the upload, report success
            return True
    except IOError:
        # could not open the file most likely
        pass
        return False

def ajax_upload( request ):
    if request.method == "POST":   
        if request.is_ajax( ):
            # the file is stored raw in the request
            upload = request
            is_raw = True
            # AJAX Upload will pass the filename in the querystring if it is the "advanced" ajax upload
            try:
                filename = request.GET[ 'qqfile' ]
            except KeyError:
                return HttpResponseBadRequest( "AJAX request not valid" )
        # not an ajax upload, so it was the "basic" iframe version with submission via form
        else:
            is_raw = False
            if len( request.FILES ) == 1:
                upload = request.FILES.values( )[ 0 ]
            else:
                raise Http404( "Bad Upload" )
            filename = upload.name

        # save the file
        success = save_upload( upload, filename, is_raw )

        # let Ajax Upload know whether we saved it or not
        import json
        ret_json = { 'success': success, }
        return HttpResponse( json.dumps( ret_json ) )

The urls.py is as follows:

####### urls.py

urlpatterns = patterns('',
(r'media/(?P<path>.*)$', 'django.views.static.serve', {'document_root':   settings.MEDIA_ROOT}),
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
url(r'^$', index,name='home'),
url( r'^ajax_upload$', ajax_upload, name="ajax_upload" ),
url( r'^upload/$', upload_page, name="upload_page" ),
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('regfields.urls')),

# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),

The code is also on: http://dpaste.com/600444/

Although everything looks fine, the upload always fails.

I use: filename = settings.UPLOAD_STORAGE_DIR, where, UPLOAD_STORAGE_DIR is definaed in settings.py as ‘/media/’

Could anyone point out where I am going wrong (Sorry, I am new to web programming and actually never used JS before, but can program in python reasonably!)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T22:13:33+00:00Added an answer on May 24, 2026 at 10:13 pm

    There is a typo in your Javascript. It should read {% csrf_token %} instead of {{ csrf_token }}.

    Edit:
    After your comments, I had a closer look at the article you linked.

    You need to include the library fileuploader.js. It will replace the placeholder div with the id file-uploader with a form with the proper event handlers. Creating a form in plain HTML will not work.

    I suggest that you have a look at the example in the Github repository: https://github.com/alexkuhl/file-uploader/tree/master/client

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So we're trying to set up replicated repositories using PlasticSCM, one in the US,
Trying to setup an SSH server on Windows Server 2003. What are some good
Trying to get my css / C# functions to look like this: body {
Trying to find some simple SQL Server PIVOT examples. Most of the examples that
Trying to make a make generic select control that I can dynamically add elements
Trying to keep all the presentation stuff in the xhtml on this project and
Trying to make a MySQL-based application support MS SQL, I ran into the following
Trying to create a QtRuby application, I get the following error: /usr/lib64/ruby/site_ruby/1.8/Qt/qtruby4.rb:2144: [BUG] Segmentation
Trying to do this sort of thing... WHERE username LIKE '%$str%' ...but using bound
Trying to perform a single boolean NOT operation, it appears that under MS SQL

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.