Change a string value to an integer


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.

celda // <--

This is my view:

  celda = request.POST.get('bonches', None)
        TC = Clasificacion.objects.filter('tabacos'))['total']
        TB = Boncheo.objects.filter('bonches'))['total']
        TN = Nacional.objects.filter('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
            TTC = TC - TB - TN

        if celda < TTC:
            valido = False
            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 class="modal-body">
    <div class="container-fluid">
        <form class="formatolinea" method="post" name="nboncheo" id="nboncheo" action='{% url "nuevobonche" %}'
        onsubmit="return boncheo();">
            {% csrf_token %}
            <select required="" name="boncheador" required="">
                <option>Nombre del bonchador</option>
                {% for obj in bonchador %}
                <option>{{obj.nombre}} {{obj.apellidos}}</option>
                {% endfor %}
            <div class="mensaje" id="mensajebr" style='display: none;'>Seleccione el nombre del bonchador</div>
            <select name="variedad">
                <option>Seleccione la variedad</option>
            <div class="mensaje" id="mensajev" style='display: none;'>Seleccione la variedad</div>
            <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>
            <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>
            <div class="mensaje" id="mensajeu" style='display: none;'>Seleccione el numero de unidades por bonche</div>
            <select required="" name="grado">
                <option>Seleccione el grado</option>
            <div class="mensaje" id="mensajeg" style='display: none;'>Seleccione el grado</div>
            <select name="lamina">
                <option>Seleccione la lamina</option>
                <optgroup label="Lamina" id="lamina1" style='display: none;'>
                <optgroup label="Lamina" id="lamina2" style='display: none;'>
                    <option>Pet Transparante con papel</option>
            <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>

And this is my ajax function:

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

3 answers


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)
>>> <class 'int'>
>>> 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
>>> 123
>>> <class 'int'>
answered by 19.10.2016 в 15:57

I think the int() function would suffice.

answered by 18.10.2016 в 21:51

if you validate correctly that is an integer in the 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