Daniel Nill
Daniel Nill

Reputation: 5747

Django FileField.save() makes duplicate files

I have user submitted content that I am trying to write to a file and then save to a FileField.

so I have a model that looks like this:

class Revision(models.Model):
    def custom_revision_file_path(instance, filename):
        return '/'.join(['content/revisions', filename])
    path = models.FileField(upload_to=custom_revision_file_path)
    document = models.ForeignKey(Document)
    ...

and the view that creates the instance looks like this:

def handle_revisions(request): 
    document = Document.objects.get(id=request.GET['docid'])
    basename = os.path.basename(str(document.path))

    revision = Revision.objects.create(
        document = document,
    )
    revision.path.save(basename, ContentFile(request.GET['revision']))

This all works relatively fine but for two problems:

1) the ContentFile puts a space between each letter in my string so 'test' turns into 't e s t' ;

2) for some reason each time I run the view two Revision instances are saved with roughly the same path. ie. one path will be 'content/revisions/test.txt' and the other will be 'content/revisions/test_1.txt' when the second one shouldn't exist at all.

What gives?

Upvotes: 2

Views: 3284

Answers (1)

Stan
Stan

Reputation: 8966

First of all, you should never use something like that to create a path :

'/'.join(['content/revisions', filename])

but :

os.path.join("my_dir", "my_subdir", ..., "filename.txt")

You are not supposed to know if your application runs on Unix-like or on Windows (yes, some people use Windows as webserver).

Also, you should not call your FileField attribute path, this is ambiguous with FilePathField.

Is this field NOT NULL ? Because in your create() statement you don't provide one. This should raise an Error.

I don't get this :

revision.path.save(basename, ContentFile(request.GET['revision']))

What are you trying to achieve ? Are you sure you want to store a GET parameter in the file ?

To answer your question, by default, Django does not take the responsability to overwrite a file that exists on your filesystem, this is why it automatically store it with an unique path by adding a suffix.

If this behaviour does not fits, consider writing a custom file storage.

Upvotes: 3

Related Questions