Problems with file upload and model forms

1,857 views
Skip to first unread message

Marc Barranco

unread,
Nov 20, 2008, 8:59:12 AM11/20/08
to Django users
Hi!
I'm trying to upload a file like the example in documentation in
Django (http://docs.djangoproject.com/en/dev/topics/http/file-
uploads/)
with the "Forms from Models".
But I can't upload the file because the form always return the error
"this field is required" although selecting a file before submitting
the form.
The fact is that I can do it with the django admin site, but with the
the my own form I don't find where's the problem.

Here is the code:

-------models.py-----------------
from django import forms
from django.forms import ModelForm
from django.db import models

class UploadFile(models.Model):
title = models.CharField(max_length=50)
file = models.FileField(upload_to="pdf/")

class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()


--------views.py---------------
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from llunes.files.models import *

def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file']) # <--In fact it never
entries here
#'cause it seems that the
#form is not valid
return HttpResponseRedirect('/files/upload/')
else:
form = UploadFileForm()
return render_to_response('files/upload.html', {'form': form})

def handle_uploaded_file(f):
destination = open('tmp.pdf', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()

Alex Koshelev

unread,
Nov 20, 2008, 9:50:41 AM11/20/08
to django...@googlegroups.com

Marc Barranco

unread,
Nov 21, 2008, 4:17:10 AM11/21/08
to Django users
Oh yeah!! It was that! Thank you veru much Alex :)

I forgot to put the template code, Here it is (mayb useful for some
other):

------upload.html------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://
www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://
www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="/media/css/forms.css" />
</head>
<body class="dashboard">
<form action="/files/upload/" enctype="multipart/form-data"
method="POST">
<table>
{% for field in form %}
<tr>
<td valign=top>{{ field.label_tag }}</td>
<td>{{ field }}
{% if field.help_text %}{{ field.help_text }}{% endif %}
{% if field.errors %}<dd class="myerrors">{{ field.errors }}</dd>
{% endif %}
</td>
</tr>
{% endfor %}

</table>
<input border=0 hspace=0 src="/media/acabar.gif" type="image"
name="Registrar" value="54" width="180" height="54"
onClick="form.submit();">
</form>
</body>
</html>
Reply all
Reply to author
Forward
0 new messages