I want to set the "default" value as a randomly generated String for the promotion_code part of my Promotion model, for that the code_generate function is used.
The issue with the code below that it seems like default=code_generate()
generates this random string once every server start thus assigning the same value. I can see that by the admin panel, every time I try to generate a new Promotion, it gives me the exact same string.
#generate a string, which is not already existing in the earlier Promotion instances
def code_generate():
while 1:
from django.conf import settings
import random, string
prom_code = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
try:
Promotion.objects.get(promotion_code=prom_code)
except:
return prom_code
class Promotion(models.Model):
purchase = models.ForeignKey('Purchase')
promotion_code = models.CharField(max_length=20,unique=True,default=code_generate())
How can I make it random ?
Regards
Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. default=value will make the field default to value.
default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).
You need to pass a callable as default
, not call the callable:
promotion_code = models.CharField(max_length=20,unique=True,default=code_generate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With