Change a string value to an integer

1

With the following code I want to make a validation where validate if a data that I am going to enter is greater than another that I already have, if so, an error message should appear.

This is what appears to me as you see the value celda takes it as a string , then I need to convert it to whole to make the comparison.

Object
TTC
:
-25
celda // <--
:
"1"
valido
:
true

This is my view:

  celda = request.POST.get('bonches', None)
        TC = Clasificacion.objects.filter(fecha=date.today()).aggregate(total=Sum('tabacos'))['total']
        TB = Boncheo.objects.filter(fecha=date.today()).aggregate(total=Sum('bonches'))['total']
        TN = Nacional.objects.filter(fecha=date.today()).aggregate(total=Sum('bonches'))['total']

        if TC == None:
            TTC = 0
        elif TB == None and TN == None:
            TTC = TC
        elif TB == None and TN != None:
            TTC = TC - TN
        elif TB != None and TN == None:
            TTC = TC - TB
        else:
            TTC = TC - TB - TN

        if celda < TTC:
            valido = False
        else: 
            valido = True
        return HttpResponse(json.dumps({'valido': valido , 'celda' : celda , 'TTC' : TTC}), content_type='application/json')

This is my template:

<div class="modal-header">
    <button type="button" class="cerrarmodal" data-dismiss="modal"><i class="fa fa-close"></i></button>
    <h4> <span><i class="fa fa-plus"></i></span>Nuevo Boncheo</h4>
</div>
<div class="modal-body">
    <div class="container-fluid">
        <form class="formatolinea" method="post" name="nboncheo" id="nboncheo" action='{% url "nuevobonche" %}'
        onsubmit="return boncheo();">
            {% csrf_token %}
            <label>Bonchador</label>
            <select required="" name="boncheador" required="">
                <option>Nombre del bonchador</option>
                {% for obj in bonchador %}
                <option>{{obj.nombre}} {{obj.apellidos}}</option>
                {% endfor %}
            </select>
            <div class="mensaje" id="mensajebr" style='display: none;'>Seleccione el nombre del bonchador</div>
            <label>Variedad</label>
            <select name="variedad">
                <option>Seleccione la variedad</option>
                <option>freedom</option>
                <option>vendela</option>
            </select>
            <div class="mensaje" id="mensajev" style='display: none;'>Seleccione la variedad</div>
            <label>Bonches</label>
            <input type="number" name="bonches" id="bonches" placeholder="Cantidad de bonches">
            <div class="mensaje" id="mensajeb" style='display: none;'>Digite el numero de bonches</div>
            <label>Unidades</label>
            <select id="unidades" name="unidades" onChange="mostrarl(this.value);" required="">
                <option>Seleccione las unidades</option>
                <option value="12">12</option>
                <option value="20">20</option>
                <option value="25">25</option>
            </select>
            <div class="mensaje" id="mensajeu" style='display: none;'>Seleccione el numero de unidades por bonche</div>
            <label>Grado</label>
            <select required="" name="grado">
                <option>Seleccione el grado</option>
                <option>40</option>
                <option>50</option>
                <option>60</option>
                <option>70</option>
            </select>
            <div class="mensaje" id="mensajeg" style='display: none;'>Seleccione el grado</div>
            <label>Lámina</label>
            <select name="lamina">
                <option>Seleccione la lamina</option>
                <optgroup label="Lamina" id="lamina1" style='display: none;'>
                    <option>Benchmark</option>
                    <option>Golden</option>
                    <option>Microcorrugada</option>
                </optgroup>
                <optgroup label="Lamina" id="lamina2" style='display: none;'>
                    <option>Pet Transparante con papel</option>
                    <option>Transparante</option>
                </optgroup>
            </select>
            <div class="mensaje" id="mensajel" style='display: none;'>Seleccione la lamina</div>
            <button class="guardar" type="button" id="button-save"><i class="fa fa-save"></i> Guardar</button>
            <button class="cancelar" type="reset" data-dismiss="modal"> <i class="fa fa-close"></i> Cancelar</button>
        </form>
    </div>

And this is my ajax function:

<script>
    $(document).ready(function() {
        $('#button-save').click(function(event) {
            $.ajax({
                type: "POST",
                url: "{% url 'validarbonche' %}",
                data: {
                    bonches: $('#bonches').val(),
                    csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val()
                },
                success:function(response) {
                    console.log(response);
                    if ('valido' in response) {
                        if (response['valido']) {
                            $('#nboncheo').submit();
                            return true;
                        }else {
                            swal("El numero de bonches es mayor a los que hay actualmente");
                            event.preventDefault();
                            event.stopPropagation();
                            return false;
                        }
                    } else {
                        console.log("no hay 'valido' en response");
                        event.preventDefault();
                        event.stopPropagation();
                        return false;
                    }
                }
            })
        })
    })
    </script>
    
asked by Angie Lizeth Santiago Piñeros 18.10.2016 в 21:05
source

3 answers

2

If you are sure that your variable of celda will always have numbers inside the string and will only have numbers, then the easiest thing is to use the function int()

celda_string = '123'
celda_numero = int(celda_string)
print(type(celda_numero))
>>> <class 'int'>
print(celda_numero)
>>> 123

Now, if you do not know exactly what you will receive in the post, which I see very possible because of the few validations you have, it is best to use regular expressions accompanied by the function int()

import re
regex = re.compile(r'\d+')
celda_int = int(regex.findall('hola123')[0]) # puede tener letras, pero solo se tendran en cuenta los números
print(celda_int)
>>> 123
print(type(celda_int))
>>> <class 'int'>
    
answered by 19.10.2016 в 15:57
1

I think the int() function would suffice.

    
answered by 18.10.2016 в 21:51
0

if you validate correctly that is an integer in the urls.py for example:

url(r'^test/view/(?P<celda>\d*)$', views.tuVista)

then it would be worth doing

def tuVista(request, celda):
    celda = int(celda)

but without parameters in the url (as you have it) it would be something like

def tuVista(request):
    celda = int(request.POST.get('bounches', 0))

Do not use None because in the int function it will show you the exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
    
answered by 19.10.2016 в 01:56