Hello, I have a model that includes a FileField. When the user uploads a file via the admin interface, I want the file to be saved as 'upload_to/ primary_key/original_filename'. Since the object will not be saved in the database when the user uploads the file, it will not have a primary key at that point. This is my workaround:
class Decision(m.Model): ... decision = m.FileField(upload_to='base_dir/') ... def save(self, *args, **kwargs): """ custom save to use pk on filename """ #save once to get a pk super(Decision, self).save(*args, **kwargs) #get info about the file uploaded = self.decision old_path = self.decision.name basedir, filename = os.path.split(old_path) new_path = os.path.join(basedir, str(self.pk), filename) #create the new file, delete the one django created uploaded.storage.save(new_path, uploaded) uploaded.storage.delete(old_path) #assign new path and save again self.decision = new_path super(Decision, self).save(*args, **kwargs) This works, but seems to be a bit on the hacky side. Basically, I'm letting FileField upload the file to the 'upload_to' path and then move it to its correct path when the object has a primary key. I was wondering if there is a better way to do this. Are there any cases where my code wouldn't work? Thanks. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.