简体   繁体   中英

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 views.py 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:

@login_required(login_url='user-login')
def SubmitApp(request):
 try:
    #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
            submit_form.save()
            messages.success(request, 'WASU 2022 Scholarship Application Submited Successfully')
            return redirect('app-slip')
    else:
        submit_form = ConfirmForm()

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

else:
    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
str(uuid.uuid4().int)[:6]

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: shortuuid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM