I want to use ajax and json so that before sending my form I validate if a field already exists in the database?

0

Hi, I need someone to help me validate, if a field is already existing in the database before sending the form and if so send me a message and return me to the form as I do?

Look, this is my view that makes the process:

def inventarioingresoe(request):
    empaque = Empaque.objects.all()
    if request.method == "POST":
        variedad = request.POST["variedad"]
        empaque = request.POST["empaque"]
        grado = request.POST["grado"]
        comercializadora = request.POST["comercializadora"]
        ramos = request.POST["ramos"]
        unidades = request.POST["unidades"]
        celda = request.POST["celda"]
        if Empaque.objects.filter(celda=celda):
            return HttpResponse(json.dumps({'valido': False}))
        else:
            nuevoingreso = Empaque.objects.create( fecha = fecha,
                                                   hora = hora,
                                                   variedad = variedad,
                                                   empaque = empaque,
                                                   grado = grado,
                                                   comercializadora = comercializadora,
                                                   ramos = ramos,
                                                   unidades = unidades,
                                                   total = int(unidades) * int(ramos),
                                                   celda = celda)
            return redirect('empaque')

    return render(request,"inventario/empaque/ingresoe.html", {})

This is my template:

<div class="modal-header">
    <button type="reset" data-dismiss="modal" class="cerrarmodal">
        <i class="fa fa-close"> </i>
    </button>
    <h4> <span><i class="fa fa-plus"></i></span>Ingresar caja</h4>
</div>
            <div class="modal-body">
                <div class="container-fluid">
                    <form class="formatolinea" method="post" name="empaque" id="empaque" action="{% url 'empaqueingreso' %}" onSubmit="return iempaque();">
                        {% csrf_token %}
                        <label>Variedad</label>
                        <select name="variedad" value="{{variedad}}">
                            <option>Seleccione la varieda</option>
                            <option>Freedom</option>
                            <option>Vendela</option>
                        </select>
                        <div class="mensaje" id="mensajev" style='display: none;'>Debe seleccionar la variedad</div>
                        <label>Grado</label>
                        <select name="grado" value='{{grado}}'>
                            <option>Seleccione el grado</option>
                            <option value="40">40</option>
                            <option value="50">50</option>
                            <option value="60">60</option>
                            <option value="70">70</option>
                        </select>
                        <div name="mensajeg" class="mensaje" id="mensajeg" style='display: none;'>Debe seleccionar el grado</div>
                        <label>Tipo de empaque</label>
                        <select name="empaque" value='{{empaque}}'>
                            <option>Seleccione el empaque</option>
                            <option>Tabaco</option>
                            <option>Full</option>
                            <option>Cuarto</option>
                            <option>Tercio</option>
                            <option>Octavos</option>
                        </select>
                        <div name="mensajee" class="mensaje" id="mensajee" style='display: none;'>Debe seleccionar el empaque</div>
                        <label>Cantidad de ramos</label>
                        <input type="number" name="ramos" value="{{ramos}}" placeholder="Digite los ramos">
                        <div name="mensajer" class="mensaje" id="mensajer" style='display: none;'>Debe digitar el numero de ramos</div>
                        <label>Unidades por ramo</label>
                         <select name="unidades" onChange="otro(this.value);">
                            <option>Unidades por ramo</option>
                            <option>20</option>
                            <option>25</option>
                            <option value="Otro" id="otro">Otro</option>
                        </select>
                        <div name="mensajeu" class="mensaje" id="mensajeu" style='display: none;'>Debe seleccionar las unidades por ramo</div>
                        <label id="digite" style=' display: none; '>Digite la cantidad</label>
                        <input type="number" name="tabaco" id="unidad" style=' display: none; ' onChange="cambiar(this.value);">
                        <label>Comercializadora</label>
                        <select name="comercializadora" value="{{comercializadora}}">
                            <option>Seleccione la comercializadora</option>
                            <option>QU</option>
                            <option>GO</option>
                            <option>FX</option>
                            <option>BG</option>
                        </select>
                        <div name="mensajec" class="mensaje" id="mensajec" style='display: none;'>Debe seleccionar la comercializadora</div>
                        <label>Numero de celda</label>
                        <input type="number" name="celda">
                        <div name="mensajecd" class="mensaje" id="mensajecd" style='display: none;'>Debe digitar el numero de celda</div>
                        <script type="text/javascript">
                        {%if mensaje %}
                        alert('{{mensaje}}')
                        document.empaque.celda.focus()
                        {% endif %}
                        </script>
                        <button class="guardar" type="submit" onclick="iempaque()"> <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>
                <!-- /.containerfluid -->
            </div>
        </div>
    </div>
</div>

What I want is that before sending the form, with ajax and json validate me in the database if the cell already exists and if so, do not redirect me to another page but keep me in it and show the message.

That's what I want.

    
asked by Angie Lizeth Santiago Piñeros 29.09.2016 в 21:51
source

2 answers

1

You are not too specific in what you ask ... but maybe this can help ...

index.js

...
$('#id_formulario').submit(function (event) {
    var form_valido;
    $.ajax({
        url: '/tu_url_para_validar_el_campo/',
        data: {'nombre_campo': valor_campo, 'csrfmiddlewaretoken': $('csrfmiddlewaretoken').val()},
        // la verdad no recuerdo el nombre de el input con el token, pero verificalo
        type: 'POST',
        success: function(data) {
            if (data['valido'] == true) {
                form_valido = true;
            } else {
                form_valido = false;
            }
        }
    })

    if (form_valido) {
        return true;
    }

    // aqui puedes poner los errores, ya sea por clases a tu campo, o un alert, por ahora pondre un alert
    alert("El campo tiene un error");
    return false;
})
...

in the view that controls the previous url, views.py

...
import json
from django.http import HttpResponse
def valida_mi_campo(request):
   if request.method == 'POST':
       try:
           Model.objects.get(id=request.POST['nombre_campo']) # el mismo string que pusiste en la data del AJAX
           return HttpResponse(json.dumps({'valido': False}), content_type='application/javascript')
       except Model.DoesNotExist:
           return HttpResponse(json.dumps({'valido': True}), content_type='application/javascript')
...

I must emphasize that this way you will still be reloading the page, which you would already be doing the work that django forms do for you ... this code is with bad practices, it would be better to use django forms to validate the fields, and not for the dictionary of 'request.POST' ... I hope I have been able to help you, any doubt comments: D

    
answered by 29.09.2016 в 22:19
-1

I would use jquery-validation, you can do exactly that apart from validating sizes etc etc,

It would be something like that, check the official doc

$( "#myform" ).validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "/check-email",
        type: "post",
        data: {
          username: function() {
            return $( "#username" ).val();
          }
        }
      }
    }
  }
});
    
answered by 30.09.2016 в 20:42