PageRenderTime 363ms CodeModel.GetById 181ms app.highlight 3ms RepoModel.GetById 178ms app.codeStats 0ms

/tests/modeltests/files/models.py

https://code.google.com/p/mango-py/
Python | 34 lines | 17 code | 8 blank | 9 comment | 0 complexity | 1f115d71467bf367b818e1c66a7d9656 MD5 | raw file
 1"""
 242. Storing files according to a custom storage system
 3
 4``FileField`` and its variations can take a ``storage`` argument to specify how
 5and where files should be stored.
 6"""
 7
 8import random
 9import tempfile
10
11from django.db import models
12from django.core.files.base import ContentFile
13from django.core.files.storage import FileSystemStorage
14
15
16temp_storage_location = tempfile.mkdtemp()
17temp_storage = FileSystemStorage(location=temp_storage_location)
18
19# Write out a file to be used as default content
20temp_storage.save('tests/default.txt', ContentFile('default content'))
21
22class 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')