Created
          October 7, 2013 13:55 
        
      - 
      
- 
        Save toast38coza/6868421 to your computer and use it in GitHub Desktop. 
    Nice dynamic upload_to method for Django FileField or ImageField
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | from django.contrib.sites.models import Site | |
| import uuid | |
| def upload_to(instance, filename): | |
| current_site = Site.objects.get_current() | |
| extension = filename.split(".")[-1] | |
| instance_slug = getattr(instance,"slug",False) | |
| if not instance_slug: | |
| instance_slug = str(uuid.uuid4()).replace("-","") | |
| return "{0}/uploads/{1}/{2}/{3}-{4}.{5}" . format (current_site.domain, instance._meta.app_label, instance._meta.module_name, instance_slug, instance.pk, extension) | |
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | ... | |
| image = models.ImageField(upload_to=upload_to) | |
| ... | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment