Avatar ·

Dynamic path for upload_to in Django model (models.FileField)

📁 lambda, Advanced Python Topics, django, AI

Hello, In Django before version 1.4 it was possible to specify a "dynamically" created file storage path in the upload_to variable for models.FileField in a model

models.py#...attach        = models.FileField(verbose_name=u'Attachment', blank=True, upload_to=lambda instance, filename: 'attach/%s/%s' % (instance.id,filename))

In Django version 1.4, it seems that id is assigned later, so instance.id = None and instance.pk = None as well. Please advise how to specify the model id in the path.

Avatar ·

Because for your task you need to use not combinations_with_replacement, but product:

import itertoolsfor i in itertools.product('0123456789', repeat=4):    print(''.join(i))

Combinations in combinatorics do not take into account the order of elements. Therefore, a set of the same elements will be considered the same combination, even if the elements are in a different order. Your code has already printed the combination of three zeros and one one (0001) once, so it will not print other variants of this combination - 0010, 0100, and 1000. The same applies to other numbers.

Log in to leave an answer

Blogs