How to recharge modal windows in Django?

0

What I want to do is that if the message is activated, the JS takes it and then reopens the modal with the form and the error, that's just it.

But I do not know how to do it.

This is the view:

def inventarioingresoe(request):
    #Codigo para calcular fecha actual
    fecha = strftime("%Y-%m-%d")
    #Codigo para calcular hora actual
    hora = strftime("%H:%M:%S")
    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):
            mensaje = 'La celda ya esta ocupada'
            return render(request,"inventario/empaque/ingresoe.html", {'mensaje' : mensaje})
        else:
            nuevoingreso = Empaque.objects.create( fecha = fecha,
                                                   hora = hora,
                                                   variedad = variedad,
                                                   empaque = empaque,
                                                   grado = grado,
                                                   comercializadora = comercializadora,
                                                   ramos = ramos,
                                                   unidades = unidades,
                                                   celda = celda)
            return redirect('empaque')

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

This is the url:

url(r'^inventario/ingreso/$', SGregorio_views.inventarioingresoe, name='empaqueingreso'),

This is the html code that calls the url:

<div class="fondosaempleados">
    <div class="container submenutercer">
        <ul class="nav-justified">
            <li>
                <a href="{% url 'empaqueingreso' %}" data-toggle="modal" data-target="#ingresoempaque"> <span><img src='{% static "img/nuevarecepcion.png" %}' alt="" class="img-responsive" title=""></span>
                    <p>NUEVO INGRESO</p>
                </a>
            </li>

This is the code of the modal window and the form:

<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" action="{% url 'empaqueingreso' %}">
            {% csrf_token %}
            <label>Variedad</label>
            <select name="variedad">
                <option></option>
                <option>Freedom</option>
                <option>Vendela</option>
            </select>
            <label>Grado</label>
            <select name="grado">
                <option></option>
                <option value="40">40</option>
                <option value="50">50</option>
                <option value="60">60</option>
                <option value="70">70</option>
            </select>
            <label>Tipo de empaque</label>
            <select name="empaque">
                <option></option>
                <option>Tabaco</option>
                <option>Full</option>
                <option>Cuarto</option>
                <option>Tercio</option>
                <option>Octavos</option>
            </select>
            <label>Cantidad de ramos</label>
            <input type="number" name="ramos">
            <label>Unidades por ramo</label>
            <select name="unidades">
                <option></option>
                <option>20</option>
                <option>25</option>
                <option>Otro</option>
            </select>
            <label>Comercializadora</label>
            <select name="comercializadora">
                <option></option>
                <option>QU</option>
                <option>GO</option>
                <option>FX</option>
                <option>BG</option>
            </select>
            <label>Numero de celda</label>
            <input type="number" name="celda">
            <div class="alert alert-danger">{{mensaje}}</div>
            <br>
            <button class="guardar" type="submit"> <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>

Function JS:

function iempaque() {
    if (document.iempaque.mensaje.value == 'La celda ya esta ocupada') {
        alert("Debe seleccionar una nueva celda")
        document.iempaque.mensaje.focus()
        return false;
    }

    alert("La informacion se ha almacenado con exito");
    document.nclasificacion.submit();

}
    
asked by Angie Lizeth Santiago Piñeros 28.09.2016 в 20:39
source

1 answer

1

My recommendation is to use what django offers you ... to do what you want to do in an easy way ... it is best that you create a Form with your fields and do not ask them in the request.POST, besides of being a good practice you save certain validations ... an example would be this in forms.py

from django import forms

class FormularioCrearEmpaque(forms.ModelForm):
    error_css_class = 'has-error' # si trabajas con bootstrap
    class Meta:
        model = Empaque
        fields = ('variedad', 'empaque', 'grado', 'comercializadora', 'ramos', 'unidades', 'celdas')

in your view of views.py you could call it

...
if request.method == 'POST':
    form = FormularioCrearEmpaque(data=request.POST)
    if form.is_valid(): # Se encargara de hacerte saber si el formulario es valido o no...
        try:
            # te haria un cambio a get y no filter porque por lo que veo, un empaque tiene una celda única... en todo caso si quieres seguir usando filter, la recomendacion de django es usar el método '.exists()'
            Empaque.objects.get(celda=form.cleaned_data['celda'])
            # podrias hacerlo asi, pero tambien es buena idea usar 'Messages' de django
            mensaje = 'La celda ya esta ocupada'
            return render(request,"inventario/empaque/ingresoe.html", {'mensaje' : mensaje})
            # si usaras Messages de Django, quedaria asi:
            # messages.error(request, "La celda ya está ocupada")
            # return render(request, "inventario/empaque/ingresoe.html", {})
        except Empaque.DoesNotExist:
            empaque = form.save(commmit=False)
            empaque.fecha = fecha
            empaque.hora = hora
            empaque.save()
            return redirect('empaque')

    else: # cuando nó es valido... asegurate de devolver al template el formulario para que pueda ser cargado en tu modal con los errores
        error = True # es una variable opcional para ayudarte a saber cuando hay error
        return render(request,"inventario/empaque/ingresoe.html", {'error': error, 'form': form})
else:
    form = FormularioCrearEmpaque()
return render(request,"inventario/empaque/ingresoe.html", {'form': form})

and after this ... all you need is your template ... in which, if you do it with this code, you will have to change the form, you could simply put a '{{form.as_p}}' and add the sumbit button ...

IMPORTANT ... you remember the variable called 'error' that you sent when the form was incorrect ... in your template

ingrese.html

...
// en algun lado en el javascript
{% if error%}
{% comment %}Aquí debe ir el codigo que haga click sobre el boton que llama a tu modal, de tal modo que cuando ocurra un error, el modal pueda ser mostrado gracias a este click{% endcomment %}
$('#ingresoempaque').click();
{% endif %}
...

I think that would be more than enough, I hope I could have helped you with your doubt

    
answered by 29.09.2016 в 15:36