This is extremely simple decorator to add possibility to upload files with name specific in some object field. For example image with same name as object slug.
Sample model:
class Test(models.Model):
image = models.ImageField(\
upload_to=upload_to_dest(path='pics/', \
human_readable_field='hrname'))
hrname = models.CharField( \
max_length=128, \
blank=True, default='')
Sample form for admin:
FNAME_EXP = re.compile('^[A-Za-z0-9\-\_]+$')
class TestAdminForm(forms.ModelForm):
hrname = forms.RegexField(
label="Human Readable File Name", \
regex=FNAME_EXP, \
help_text="""Allowed only latin alphabet
(upper and lower cases),
underscore and minus
characters. PLEASE, DO NOT INCLUDE
EXTENSION OF THE FILE.
Sample: test-this-file""", \
required=False)
class Meta:
model = Test
Sample admin.py for Test model:
class TestAdmin(admin.ModelAdmin):
form = TestAdminForm
admin.site.register(Test, TesetAdmin)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def upload_to_dest(path='', human_readable_field='hrfname'):
def unique_filepath(instance, filename):
"""Generate random unique filename or use name
from `human_readable_field` if it's available and not empty"""
fname, ext = os.path.splitext(filename)
if hasattr(instance, human_readable_field) and \
getattr(instance, human_readable_field) and \
getattr(instance, human_readable_field) != '':
fname_chunk = getattr(instance, human_readable_field)
else:
fname_chunk = uuid.uuid4()
filename = "%s%s" % (fname_chunk, ext.lower())
return os.path.join(path, filename)
return unique_filepath
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Change this:
to:
#
Please login first before commenting.