Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce unique upload file names using django?

What's the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any pinax apps that can do this, perhaps with GUID?

like image 691
zjm1126 Avatar asked Apr 20 '10 08:04

zjm1126


1 Answers

Use uuid. To tie that into your model see Django documentation for FileField upload_to.

For example in your models.py define the following function:

import uuid import os  def get_file_path(instance, filename):     ext = filename.split('.')[-1]     filename = "%s.%s" % (uuid.uuid4(), ext)     return os.path.join('uploads/logos', filename) 

Then, when defining your FileField/ImageField, specify get_file_path as the upload_to value.

file = models.FileField(upload_to=get_file_path,                         null=True,                         blank=True,                         verbose_name=_(u'Contact list')) 
like image 170
Nathan Avatar answered Oct 02 '22 17:10

Nathan