parts/django/tests/modeltests/files/models.py
changeset 307 c6bca38c1cbf
equal deleted inserted replaced
306:5ff1fc726848 307:c6bca38c1cbf
       
     1 """
       
     2 42. Storing files according to a custom storage system
       
     3 
       
     4 ``FileField`` and its variations can take a ``storage`` argument to specify how
       
     5 and where files should be stored.
       
     6 """
       
     7 
       
     8 import random
       
     9 import tempfile
       
    10 
       
    11 from django.db import models
       
    12 from django.core.files.base import ContentFile
       
    13 from django.core.files.storage import FileSystemStorage
       
    14 
       
    15 
       
    16 temp_storage_location = tempfile.mkdtemp()
       
    17 temp_storage = FileSystemStorage(location=temp_storage_location)
       
    18 
       
    19 # Write out a file to be used as default content
       
    20 temp_storage.save('tests/default.txt', ContentFile('default content'))
       
    21 
       
    22 class Storage(models.Model):
       
    23     def custom_upload_to(self, filename):
       
    24         return 'foo'
       
    25 
       
    26     def random_upload_to(self, filename):
       
    27         # This returns a different result each time,
       
    28         # to make sure it only gets called once.
       
    29         return '%s/%s' % (random.randint(100, 999), filename)
       
    30 
       
    31     normal = models.FileField(storage=temp_storage, upload_to='tests')
       
    32     custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
       
    33     random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
       
    34     default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')