2009/7/1 Rajesh D <rajesh.dha...@gmail.com>: > Judging by the discussions on the above mentioned ticket, it may be a > while before this behaviour is reverted back (if it is reverted back > at all.)
I'm not seeking to have the new behaviour reversed - if the powers that be say the new way is more robust, I'm happy to go along with that. But I think it is important to realise that it is a backwards incompatible change, and there are real use cases for the old behaviour. > There's a subtle bug in this line of your code: > > self.slug = self.photo.url.split('/')[-1:][0].split('.')[0] > > It assumes that the expression will never result in a slug whose > length is more than 16. But that's not necessarily true because when > Django tries to save your photo file and finds another file with the > same name, it will append an underscore to the filename until it > generates a unique filename. In that case, your slug will extend > beyond its 16 character limit. Since your filenames are generated > randomly, it's not very likely that you will ever hit this edge case. > But just be aware. Duplicate filenames are checked for elsewhere in my code (I only presented a truncated version for clarity), so there shouldn't be a case where underscores are used, and the slug will always be unique (unless there are so many uploads, I run out of 16 hex digit combinations!). > As for your problem of computing a slug based on the filename, perhaps > the following will help: > > def get_path(instance, filename): > salt = hashlib.sha1(str(random.random())).hexdigest() > name = hashlib.sha1(salt+filename).hexdigest()[:16] > # Save generated filename in an attribute of this model instance: > instance._my_filename = name > return '%s.jpg' % (name) > > Then, in the model save do: > > if not self.slug: > self.slug = self._my_filename > > If this does work, you might still have to add some more defensive > code around there to check that the instance "hasattr" _my_filename > and if it doesn't, may be just generated a random 16 character slug. I don't think this will work, as get_path() will not be called until the model is saved. So the _my_filename attribute will not be available to the code in the save method before the super(Photo, self).save() line. Would it be possible to define the hashed filename in the save method, and then pass it to the upload_to argument of the ImageField? Thank you for your reply, Andrew --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---