paulocheque / django-dynamic-fixture

A complete library to create dynamic model instances for testing purposes.
http://django-dynamic-fixture.readthedocs.io/
Other
391 stars 67 forks source link

Creating files for ImageField and FileField fields #10

Closed saippuakauppias closed 4 years ago

saippuakauppias commented 12 years ago

I'm writing custom fixture class for creating uploaded files. But this code must be in a package.

import os

from django.conf import settings
from django.core.files import images, File

from django_dynamic_fixture.\
    fixture_algorithms.sequential_fixture import SequentialDataFixture

image_path = os.path.join(settings.PROJECT_ROOT, 'static', 'images',
                          'logo.png')

class FixedFilesFixture(SequentialDataFixture):

    def filepathfield_config(self, field, key):
        return image_path

    def filefield_config(self, field, key):
        with open(image_path, 'rb+') as fh:
            return File(fh)

    def imagefield_config(self, field, key):
        with open(image_path, 'rb+') as fh:
            return images.ImageFile(fh)
paulocheque commented 11 years ago

Hi there, thanks for your suggestion. This is the current code to deal with FileFields.

        django_file = data
        if isinstance(django_file, File):
            setattr(instance, field.name, data.name) # set the attribute
            if django_file.file.mode != 'rb':
                django_file.file.close() # this file may be open in another mode, for example, in a+b
                opened_file = open(django_file.file.name, 'rb') # to save the file it must be open in rb mode
                django_file.file = opened_file # we update the reference to the rb mode opened file
            getattr(instance, field.name).save(django_file.name, django_file) # save the file into the file storage system
            django_file.close()
        else: # string (saving just a name in the file, without saving the file to the storage file system
            setattr(instance, field.name, data) # Model.field = data
theskumar commented 8 years ago

@paulocheque I've been working with files. Things work fine except that the above code tries to prematurely save the model instance while saving the image file to storage, causing IntegrityError:

It can be corrected by replacing:

getattr(instance, field.name).save(django_file.name, django_file) # save the file into the file storage system
django_file.close()

with

getattr(instance, field.name).save(django_file.name, django_file, save=False)

Notice the save=False and removed django_file.close()

Cheers, and thanks for an awesome library!

paulocheque commented 8 years ago

The 1.9.0 version included your suggestion. Thanks!

theskumar commented 8 years ago

Thanks @paulocheque! 😊