views:

126

answers:

3

I'm trying to create a "cool" image uploading interface in django admin panel. The problem is that I'm using inline interface for uploading image instances, but I'm using jQuery Ajax form to upload images, so there were another form I need to create for uploading. And now django view function can't receive request.FILES from this form, because I've created it without using django.forms and can't specify in view function which form needs to be used. So I can't override standard view function for inline interfaces and can't recreate this form using django.forms. So this code doesn't seem to work:

My form:

<form id="uploadForm" enctype="multipart/form-data" method="post" action="upload_picture/">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

My view function:

def upload_picture(request):
    if request.method == 'POST':
        save_original(request.FILES['file'])
    return HttpResponseRedirect('admin/edit_inline/picture_editor.html')

Maybe I should make it completely different way?

A: 

I tested this code, and files are uploaded just fine. Can you show the jquery that you're using to construct your form with?

Thanks.

Mike
A: 

I suggest using a template fragment which generates the form , but which also can be generated seperately and sent to the jquery. this preservers CSRF tokens and allows tou to parse the file with forms correctly

for instance you would use:

$.ajax({
    url: "/uploadPicture?JustForm",
    dataType: ($.browser.msie) ? "text" : "html",
    success: function(data){
        // Put the form contained in data onto the page (it's a string)
        $("formContainer").innerHtml(data)
    }
});

then have your form as returned directly by your view

def upload_picture(request):
    if request.GET.has_key('JustForm'):
        return YourFormObject.as_html() <- will include CSRF tags for compat with 1.2
    if request.method == 'POST':
        save_original(request.FILES['file'])
    return HttpResponseRedirect('admin/edit_inline/picture_editor.html')

(disregard blatent errors, treat like pseudocode)

Thomas
A: 

This tutorial can help.

http://embrangler.com/2010/08/ajax-uploads-images-in-django/

Abe