This page describes how file uploads work in BlogEngine.

File uploads in BlogEngine is supported using standard Django newforms API with very little exceptions.

For example, to upload a file using a forms.Form subclass, one can use a CharField class as place-holder, then manually handle the file upload using the shutil module, as described here.

   1 from django import forms
   2 class AddEntryForm(forms.Form):
   3     ...
   4     # source file (rst or markdown formats) to upload and convert
   5     # in sanitized markup
   6     source = forms.CharField(required=True, label=_('File'), widget=forms.FileInput(), ...)

Here's the relevant code used in a generic view to upload a file to a given local directory. To use, copy/paste as necessary... ;)

   1 if request.method == 'POST':
   2     new_data = request.POST.copy()
   3     tmpFile = new_data['source']
   4     def handle_file_upload(f):
   5         filename = os.path.join(permanent_store, f.filename.lstrip(os.sep))
   6         permFile = open(filename, 'w')
   7         shutil.copyfileobj(f.file, permFile)
   8         f.file.close()
   9         permFile.close()
  10         #logger.debug("Saved a new file: %s" % filename)
  11         return filename
  12 
  13     form = AddEntryForm(new_data)
  14     if form.is_valid():
  15         # Continue with schevo model validation
  16         cleaned_data = form.cleaned_data
  17         db = request.environ[settings.DATABASE_NAME] # schevo.db.blogengine
  18 
  19         # form hack: make the source attribute a filepath and handle the
  20         # file upload under the scene.. :)
  21         cleaned_data['source'] = handle_file_upload(tmpFile)


CategoryBlogEngine, CategoryTipsAndTricks

just another Wiki: BlogEngine/FileUploads (last edited 2010-05-10 23:22:48 by anonymous)