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?
request.FILES should work fine with that handmade form. Django doesn't do anything different with the field except adding the id="id_file". I'm fairly certain that your not having an id wouldn't interfere with the transference into request.FILES.
In [5]: from django import forms
In [6]: class GenericFileForm(forms.Form):
...: file = forms.FileField()
...:
In [7]: g = GenericFileForm()
In [8]: print g
<tr><th><label for="id_file">File:</label></th><td><input type="file" name="file" id="id_file" /></td></tr>
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.
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)
This tutorial can help.
http://embrangler.com/2010/08/ajax-uploads-images-in-django/
精彩评论