How can I automatically generate unique 4 digits and save in Django Model


I am working on a project in Django where I have a SubmitedApps Model which is intended for all submitted applications. Below is the model code:

class SubmitedApps(models.Model):
    applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4)
    confirm = models.BooleanField()
    date = models.DateTimeField(auto_now_add=True)

def save(self, *args, **kwargs):
     self.application == str(uuid.uuid1())
     super().save(*args, **kwargs)

def __unicode__(self):
    return self.applicant

def __str__(self):
    return f'Application Number: {self.application} Username:{self.applicant}'

I also have a ModelForm which is a checkbox as shown below:

class ConfirmForm(forms.ModelForm):
confirm = forms.BooleanField()
class Meta:
    model = SubmitedApps
    fields = ['confirm'] 

In the I have try to check if the application was already submitted, and if not it should be submitted else it should redirect the applicant to Application Print Out Slip Page as shown below:

def SubmitApp(request):
    #Grab the logged in applicant in the submited app table
    check_submited = SubmitedApps.objects.get(applicant=request.user)
#If it Does NOT Exist then submit it
except SubmitedApps.DoesNotExist:
    if request.method == 'POST':
        submit_form = ConfirmForm(request.POST, request.FILES)
        if submit_form.is_valid():
            submit_form.instance.applicant = request.user
            messages.success(request, 'WASU 2022 Scholarship Application Submited Successfully')
            return redirect('app-slip')
        submit_form = ConfirmForm()

    context = {
    return render(request, 'user/confirmation.html', context)

    if check_submited.application != "":
        return redirect('app-slip')

My problem is that the auto generated output are NOT NUMBERS but cb4f5e96-951e-4d99-bd66-172cd70d16a5 whereas I am looking forward to 4 to 6 Digits Unique Numbers.


you can use UUIDField it’s custom and it’s from Django model built in ,

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # other fields

and to custom only digit and from 4 to 6 , you can do the following :

import uuid

and finally code will do :

import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=str(uuid.uuid4().int)[:6], editable=False)
    # other fields

A better idea would be to generate a cryptographic token with the desired length. This also has the possibility of collisions, but I imagine it would be much less than a truncated UUID.

Other Solution:
to use this library:

Answered By – Ahmad Akel Omar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published