Django while True try loop in createview

I hope I am not being a little paranoid but I am trying to make that when there is a record or customer number the next record is different from the previous one, the reason why I do it this way is because there will be many people capturing data at the same time every day and I do not want to throw a 404 error or something like that but on the contrary, in case there is already a record in the database retry and retry and retry again. This is an example that I need to conclude to finish well my script, obviously before it makes a request to the database to verify the last record.

I know it is possible to do this with function based views but at the moment I am testing class based views, I have been doing this for several hours. Any help is very important to me. Thanks guys.

models.py

from django.db import models

# Create your models here.

class Empresa(models.Model):
    nombre = models.CharField(max_length=20)
    numero = models.IntegerField(unique=True)

views.py

from dataclasses import field
from django.shortcuts import render
from django.views.generic import *

from aplicacion.models import Empresa

# Create your views here.

class CrearEmpresa(CreateView):
    model = Empresa
    template_name = 'crearempresa.html'
    success_url  = '/crear/'
    fields = ['nombre', 'numero']

    valor = 0
    
    def form_valid(self, form):
        x = form.save(commit=False)
        x.numero = self.valor

        while True:
            try:
                x.save()
                return super().form_valid(form)
                break
            
            except:
                self.valor = self.valor + 1
                pass
Back to Top