Can't figure out file upload

85 views
Skip to first unread message

Maniac

unread,
Sep 8, 2005, 5:57:48 AM9/8/05
to django...@googlegroups.com
I can't figure out a very simple file upload. I have a simple model with
one-to-many relation:

class Dashboard(meta.Model):
name=meta.CharField(maxlength=20)

class Thumbnail(meta.Model):
dashboard=meta.ForeignKey(Dashboard)
image=meta.ImageField(upload_to='...')

1. First problem is that Django renders <input type="hidden"> instead of
<input type="file">. Here's my View to render the form:

def dashboard(request):
Manipulator=thumbnails.AddManipulator()
Form=formfields.FormWrapper(Manipulator,{},{})
Template=template_loader.get_template('orders/dashboard')
Context=DjangoContext(request, {
'form':Form,
})
return HttpResponse(Template.render(Context))

and {{ form.image }} gives me this:

<input type="hidden" id="id_image" name="image" value="" />

2. When I create this field manually I can't save the uploaded data.
Here's the View for saving:

def upload(request):
new_data=request.POST.copy()
new_data.update(request.FILES)
Manipulator=thumbnails.AddManipulator()
Manipulator.do_html2python(new_data)
Thumbnail=Manipulator.save(new_data)
return HttpResponseRedirect('/dashboard/')

This gives me an exception:

ProgrammingError: ERROR: syntax error at or near "{" at character 65

INSERT INTO orders_thumbnails (dashboard_id,image) VALUES
(NULL,{'content': '\xff\xd8\.....

Looks like I can't persuade Django that this is actually a file field
and it treats it as plain text.

3. Another problem is that it tries to insert NULL in 'dashboard_id'
which certainly won't work when you kindly help me get this file in
proper form :-). Currently I fix it like this:

new_data['dashboard']=ObtainDashboard(request).id

where ObtainDashboard is my custom function that returns live Dashboard
instance. But it seems very low-level work from which I heartily wish
Django could save me.

Somewhat frsurtrated I am... Please help!

Dagur

unread,
Sep 8, 2005, 6:52:00 AM9/8/05
to Django users
I've been throught this too :)

First of all, you need to use both {{ form.image}} and {{
form.image_file }}
this will create the hidden file and the file input field.

Also, if you forgot like I did, you need to put

enctype="multipart/form-data"

into the form tag.

Thirdly, in the view, do this:

if request.POST:
new_data = request.POST.copy()
new_data.update(request.FILES) # This has to be added

errors = manipulator.get_validation_errors(new_data)
if not errors:
new_message = manipulator.save(new_data)


Good luck, I hope this helps

Maniac

unread,
Sep 8, 2005, 11:33:55 AM9/8/05
to django...@googlegroups.com
Dagur wrote:

>First of all, you need to use both {{ form.image}} and {{
>form.image_file }}
>
>
Ah! This did it. Thank you very much!
Reply all
Reply to author
Forward
0 new messages