mardi 8 juin 2021

Is there a way to generate random integers using django forms.py?

I just started learning Django and have a problem:

I initially used a class-based view to save information from the front end or user. I then decided to switch to forms.py.

My problem is I cannot generate a random number to be saved using forms.py.

I do not know if I should recreate this in forms or models.

This was the code I wrote in views.py:

def createproformastandard(request):

    now = datetime.datetime.now()
    year = now.year
    month = now.month
    day = now.day

    if len(str(day)) == 1:
        day = "0" + str(day)
    if len(str(month)) == 1:
        month = "0" + str(month)

    today = str(year) + "/" + str(month) + "/" + str(day)

    date = str(year) + str(month) + str(day)
    randint = str(random.randint(1000, 9999))
    rand = str("TSCL") + date + "-" + randint + str("-P")
    rand = str(rand)

    while len(ProformaReceipt.objects.filter(rand=rand)) != 0:
        randint = str(random.randint(1000, 9999))
        rand = date + randint
        rand = int(rand)

    form = CreateProformaReceipt()
    if request.method == 'POST':
        form = CreateProformaReceipt(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')

    context = {'form': form}
    return render(request, 'proforma/proforma_form_standard.html', context)



Aucun commentaire:

Enregistrer un commentaire