分类:
2008-11-09 16:01:37
Some interesting examples on how to handle file uploads using :
save()
method in the form class. This method is invoked when calling form.save()
, which is standard Django newforms practice. (Note that this snipped uses clean_data
. As of Django version 0.96, clean_data
to cleaned_data
, so you will have to change the code or it won’t work)save_FOO_file
method. (This method is automatically provided by Django for fields declared as models.ImageField
or models.FileField
in the model. See the db-api documentation.)request.user
by calling form_for_instance
.
The resulting class in then monkey-patched to insert the avatar image
validation code. (Although the code is interesting the monkey patch
seems unnecessary. I wouldn’t mind inserting the avatar validation
method in a UserProfileForm
class derived from form.Forms
. The code would be certainly clearer: I think KISS takes precedence over DRY in this case.)Interesting, there seems to be no easy way of limiting the uploaded file size. The file can be rejected at validation time, but the data would have already been transfered.
After reading those posts, I think that a good recipe for handling file uploads in Django would be:
form.Forms
and declare a clean_FOO
method for each models.FileInput
or models.ImageInput
fields declared in the model class. These clean_FOO methods are used to validate the uploaded files.is_valid()
.request.FILES
object, by writing a save()
method for the subclassed form or by calling save_FOO_file
for the model instance.The following short
example uses no data models, does no data validation, and saves the
file directly to disk using python standard file functions. It is just
a simple test I wrote to get familiar with the request.FILES
object. This is not production code: it could be used to execute an arbitrary script on the server.
The directory where the file is to be saved must be writable by the
user that is running the Django server script. (The example uses
MEDIA_ROOT as defined in settings.py
.)