All I want is to generate a unique code preferably a mix of both letters and numbers when I create a Model Class called Competition
in django. I want to use this code as a reference code for users to be able to fill in a form that will allow them to join that specific Competition
.
I have this code in my models.py
:
class Competition(models.Model):
name = models.CharField(max_length=100)
location = models.CharField(max_length=50)
no_of_rounds = models.IntegerField(validators= [MinValueValidator (1, message='Please enter a number greater than or equal to 1'), MaxValueValidator (30, message='Please enter a number less than or equal to 30')])
gates_per_round = models.IntegerField(validators= [MinValueValidator (1), MaxValueValidator (30)])
ref_code = models.CharField(
max_length = 10,
blank=True,
editable=False,
unique=True,
default=get_random_string(10, allowed_chars=string.ascii_uppercase + string.digits)
)
def __str__(self):
return self.name
Preferably I don't want the unique code field to be a primary key if possible and that's why I have that field called ref_code
. I tried creating a competition, which generated me this code LZDMGOQUFX. I am also wondering why the code only consists of letters. Anyways I tried creating a different competition but it raises an IntegrityError
that says UNIQUE constraint failed
in my ref_code
field. Someone send help, thanks.