I need a little bit of help here.
I want to let user to import a csv file which will be parsed into the
database.
I am thinking of using FileField to let the user choose the file (with
the browse button) but I am having some difficulty parsing it.
I was thinking of using csv library from python to do the parsing but
to use that library I would need to get the full pathname of the files
while FileField only gives the name of the file and the content of the
file.
I tried using CharField(widget = forms.FileInput) but it gives exactly
the same results.
Seems like I could not get the full pathname of the file no matter
what.
Perhaps Im missing something here and hopefully someone can point me
out cause I dont want to do the low level processing myself to parse
those csv files directly (without using csv library)
Thanks
Ronald
Your solution will work for models but I am using forms and I m not
sure if instance of form has similar method such as get_FOO_filename.
Sorry i wasnt really clear before and I hope someone here can help me
again.
Thanks
Ronald
html
<form action="/test" method="post" enctype="multipart/form-data">
<input type="file" name="photo" />
save data
new_data = request.POST.copy() # these two lines
are
new_data.update(request.FILES) # very important
form = ThingForm(new_data)
if form.is_valid():
clean_data = form.clean_data
t = Thing()
t.name = clean_data['name']
if clean_data['photo']:
photo = clean_data['photo']
t.save_photo_file(photo['filename'],
photo['content'])
you can also eliminate model and save directly to some binary stream
These two lines are no longer important. An alternate approach to
handling file input was recently introduced to the SVN trunk version
of Django.
You might want to look at the documentation for newforms, in particular:
http://www.djangoproject.com/documentation/newforms/#binding-uploaded-files-to-a-form
http://www.djangoproject.com/documentation/newforms/#filefield
http://www.djangoproject.com/documentation/newforms/#imagefield
These describes the correct procedure for handling File input with newforms.
Yours,
Russ Magee %-)
Your question is slightly ill-posed. Form.FileField doesn't have a
get_FOO_filename equivalent because it doesn't have any responsibility
for saving (or storing) a file on disk. As such, there is no such
thing as 'the full path to the file' - there is only the name of the
file as supplied to the form, and the contents of the file selected by
the form.
If you want to save something permanently, you need to associate it
with a model FileField (which provides an upload_to directory into
which the file content can be placed), or you need to roll your own
scheme for determining a server-side file location from form input.
Yours,
Russ Magee %-)