Hi,

I have model Object and I want to store 0..N files
for each. To keep the files together the files should
be saved under a directory like this: .../objects/ID/

FileField does not support this. Now I found a simple
solution, that I want to share. 

The solution is simple: I don't need FileField. 
It is redundant to store the file names in the database.
An other point: there is a break in the transaction flow 
(filesystem can't rollback like a database).

I just upload to .../objects/ID/ and there is a method
of the model Object which returns the list of all uploaded files. This
just calls os.listdir().

Here is the code, which uses urlquote() to convert the unicode filenames.

# Python
import os
import urllib

# Django
from django.conf import settings
from django.utils.http import urlquote

class Attachment(object):
    def __init__(self, obj, filename=None, fs_name=None):
        self.obj=obj
        if filename:
            assert not fs_name
            self.filename=filename
        else:
            assert not filename
            self.filename=urllib.unquote(fs_name)
        assert self.filename.find("/")==-1, self.filename

    def __cmp__(self, other):
        assert isinstance(other, Attachment), other
        return cmp(self.fs_name, other.fs_name)

    def __repr__(self):
        return '<%s.%s %s>' % (self.__class__.__module__, 
self.__class__.__name__, self.fs_name)
    
    def get_directory(self):
        return os.path.join(settings.ATTACHMENT_UPLOAD_TO, str(self.obj.id))
    directory=property(get_directory)
    
    def get_fs_name(self):
        fs_name=urlquote(self.filename)
        return os.path.join(self.directory, fs_name)
    fs_name=property(get_fs_name)

    def get_absolute_url(self):
        return urlquote("%sobject/%d/attachment/%s" % (
            settings.SCRIPTNAME, self.obj.id, self.filename))

    def delete(self):
        os.unlink(self.fs_name)


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to