Conjunto 3625c13 en participacion_consulta


Ignorar:
Fecha y hora:
03/10/2017 15:08:34 (hace 7 años)
Autor:
rudmanmrrod <rudman22@…>
Branches:
master
Children:
14afbd3
Parents:
fd72443
Mensaje:

Añadidas funciones para cargar los municipios y parroquias de acuerdo al seleccionado, todo por REST

Ficheros:
7 editados

Leyenda

No modificado
Añadido
Eliminado
  • base/functions.py

    rd923030 r3625c13  
    2020import requests
    2121
    22 def cargar_tipo_pregunta():
    23     """!
    24     Función que permite cargar los tipos de preguntas que existen
    25 
    26     @author Rodrigo Boet (rboet at cenditel.gob.ve)
    27     @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a>
    28     @date 15-02-2017
    29     @return Devuelve una tupla con los tipos de pregunta
    30     """
    31 
    32     lista = ('', 'Seleccione...'),
    33 
    34     try:
    35         for tipo_pregunta in TipoPregunta.objects.all():
    36             lista += (tipo_pregunta.id, tipo_pregunta.tipo),
    37     except Exception as e:
    38         pass
    39 
    40     return lista
    4122
    4223def cargar_entidad():
     
    5334
    5435    try:
    55         for entidad in Entidad.objects.all():
    56             lista += (entidad.codigo, entidad.nombre),
    57     except Exception as e:
    58         pass
    59 
    60     return lista
    61 
    62 
    63 def cargar_municipios():
     36        entidades = requests.get(API_URL+'entidad/')
     37        for entidad in entidades.json():
     38            lista += (entidad['codigo'], entidad['nombre']),
     39    except Exception as e:
     40        pass
     41
     42    return lista
     43
     44
     45def cargar_municipios(entidad = 0):
    6446    """!
    6547    Función que permite cargar todas los municipios
     
    6850    @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a>
    6951    @date 20-04-2017
     52    @param entidad <b>{int}</b> Recibe el id del padre
    7053    @return Devuelve una tupla con los municipios
    7154    """
     
    7457
    7558    try:
    76         for municipio in Municipio.objects.all():
    77             lista += (municipio.codigo, municipio.nombre),
    78     except Exception as e:
    79         pass
    80 
    81     return lista
    82 
    83 
    84 def cargar_parroquias():
     59        url = API_URL+'municipio/' if entidad ==0 else API_URL+'municipio/?estado='+str(entidad)
     60        municipios = requests.get(url)
     61        for municipio in municipios.json():
     62            lista += (municipio['codigo'], municipio['nombre']),
     63    except Exception as e:
     64        pass
     65
     66    return lista
     67
     68
     69def cargar_parroquias(municipio = 0):
    8570    """!
    8671    Función que permite cargar todas las parroquias
     
    8974    @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a>
    9075    @date 20-04-2017
     76    @param municipio <b>{int}</b> Recibe el id del padre
    9177    @return Devuelve una tupla con las parroquias
    9278    """
     
    9581
    9682    try:
    97         for parroquia in Parroquia.objects.all():
    98             lista += (parroquia.codigo, parroquia.nombre),
     83        url = API_URL+'parroquia/' if municipio ==0 else API_URL+'parroquia/?municipio='+str(municipio)
     84        parroquias = requests.get(url)
     85        for parroquia in parroquias.json():
     86            lista += (parroquia['codigo'], parroquia['nombre']),
    9987    except Exception as e:
    10088        pass
  • base/templates/base.vars.javascript.html

    rd923030 r3625c13  
    11{% load static from staticfiles %}
    22<script type="text/javascript">
    3     // URL para actualizar el combo
    4     var URL_ACTUALIZAR_COMBO = "{% url 'actualizar_combo' %}" ;
     3    // URL para obtener municipios
     4    var URL_BUSCAR_MUNICIPIO = "{% url 'buscar_municipio' %}" ;
     5   
     6    // URL para obtener parroquias
     7    var URL_BUSCAR_PARROQUIA = "{% url 'buscar_parroquia' %}" ;
    58
    69    // URL para participación
  • base/urls.py

    rf29adf8 r3625c13  
    2222## Ajax
    2323urlpatterns +=[
    24     url(r'^ajax/actualizar-combo/?$', actualizar_combo, name='actualizar_combo'),
     24    url(r'^ajax/municipio/?$', buscar_municipio, name='buscar_municipio'),
     25    url(r'^ajax/parroquia/?$', buscar_parroquia, name='buscar_parroquia'),
    2526]
  • base/views.py

    rd923030 r3625c13  
    1414# @version 1.0
    1515from django.shortcuts import render
    16 from django.http import HttpResponse
     16from django.http import JsonResponse
    1717from django.apps import apps
    1818from django.views.generic import TemplateView
    1919from django.contrib.auth.mixins import LoginRequiredMixin
     20from base.functions import cargar_municipios, cargar_parroquias
    2021
    2122import json
     
    3334
    3435
    35 def actualizar_combo(request):
     36def buscar_municipio(request):
    3637    """!
    37     Función que actualiza los datos de un select dependiente de los datos de otro select
     38    Función buscar municipios (se puede filtrar por la entidad)
    3839
    39     @author Ing. Roldan Vargas (rvargas at cenditel.gob.ve)
     40    @author Rodrigo Boet (robet at cenditel.gob.ve)
    4041    @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a>
    41     @date 28-04-2016
     42    @date 03-10-2017
    4243    @param request <b>{object}</b> Objeto que contiene la petición
    43     @return Devuelve un HttpResponse con el JSON correspondiente a los resultados de la consulta y los respectivos
    44             elementos a cargar en el select
     44    @return Devuelve un JsonResponse con los datos
    4545    """
    46     try:
    47         if not request.is_ajax():
    48             return HttpResponse(json.dumps({'resultado': False, 'error': str('La solicitud no es ajax')}))
     46    entidad = request.GET.get('entidad',None)
     47    if(entidad):
     48        data = cargar_municipios(entidad)
     49    else:
     50        data = cargar_municipios()
     51    return JsonResponse(data,safe=False)
    4952
    50         ## Valor del campo que ejecuta la acción
    51         cod = request.GET.get('opcion', None)
     53def buscar_parroquia(request):
     54    """!
     55    Función buscar parroquias (se puede filtrar por el municipio)
    5256
    53         ## Nombre de la aplicación del modelo en donde buscar los datos
    54         app = request.GET.get('app', None)
    55 
    56         ## Nombre del modelo en el cual se va a buscar la información a mostrar
    57         mod = request.GET.get('mod', None)
    58        
    59         ## Atributo por el cual se va a filtrar la información
    60         campo = request.GET.get('campo', None)
    61 
    62         ## Atributo del cual se va a obtener el valor a registrar en las opciones del combo resultante
    63         n_value = request.GET.get('n_value', None)
    64 
    65         ## Atributo del cual se va a obtener el texto a registrar en las opciones del combo resultante
    66         n_text = request.GET.get('n_text', None)
    67 
    68         ## Nombre de la base de datos en donde buscar la información, si no se obtiene el valor por defecto es default
    69         bd = request.GET.get('bd', 'default')
    70 
    71         filtro = {}
    72 
    73         if app and mod and campo and n_value and n_text and bd:
    74             modelo = apps.get_model(app, mod)
    75            
    76             if cod:
    77                 filtro = {campo: cod}
    78 
    79             out = "<option value=''>%s...</option>" % str("Seleccione")
    80 
    81             combo_disabled = "false"
    82 
    83             if cod != "" and cod != "0":
    84                 for o in modelo.objects.using(bd).filter(**filtro).order_by(n_text):
    85                     out = "%s<option value='%s'>%s</option>" \
    86                           % (out, str(o.__getattribute__(n_value)),
    87                              o.__getattribute__(n_text))
    88             else:
    89                 combo_disabled = "true"
    90 
    91             return HttpResponse(json.dumps({'resultado': True, 'combo_disabled': combo_disabled, 'combo_html': out}))
    92 
    93         else:
    94             return HttpResponse(json.dumps({'resultado': False,
    95                                             'error': str('No se ha especificado el registro')}))
    96 
    97     except Exception as e:
    98         return HttpResponse(json.dumps({'resultado': False, 'error': e}))
     57    @author Rodrigo Boet (robet at cenditel.gob.ve)
     58    @copyright <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GNU Public License versión 3 (GPLv3)</a>
     59    @date 03-10-2017
     60    @param request <b>{object}</b> Objeto que contiene la petición
     61    @return Devuelve un JsonResponse con los datos
     62    """
     63    municipio = request.GET.get('municipio',None)
     64    if(municipio):
     65        data = cargar_parroquias(municipio)
     66    else:
     67        data = cargar_parroquias()
     68    return JsonResponse(data,safe=False)
  • static/js/funciones.js

    rd923030 r3625c13  
    1 /**
    2  * Función para agregar preguntas en la consulta
    3  * @param element Recibe nombre de elemento a agregar
    4 **/
    5 function agregar_preguntas(element) {
    6     $('#agregar_preguntas').append($(element).html());
    7 }
    8 
    9 /**
    10  * Función para eliminar preguntas agregadas dinámicamente
    11  * @param element Recibe el elemento a partir del cual se eliminará la fila
    12 **/
    13 function eliminar_preguntas(element) {
    14     $(element).parent().parent().parent().remove();
    15 }
    16 
    17 /**
    18  * Función para validar las preguntas agregadas dinámicamente
    19  * @param event Recibe el evento click
    20 **/
    21 function validar_preguntas(event) {
    22     var longitud = $('#agregar_preguntas').find('.row');
    23     if(longitud.length>0)
    24     {
    25         var vacio = false;
    26         $.each(longitud.find('input'),function(key,value){
    27             if ($(value).val().trim()=='') {
    28                 vacio = true;
    29             }
    30         });
    31         $.each(longitud.find('select'),function(key,value){
    32             if ($(value).val().trim()=='') {
    33                 vacio = true;
    34             }
    35         });
    36         if (vacio) {
    37             event.preventDefault();
    38             bootbox.dialog({
    39                 message: "Debe llenar todas las preguntas que agregó",
    40                 title: "<b class='text-danger'>Error</b>",
    41                 buttons: {
    42                     success: {
    43                         label: "Cerrar",
    44                         className: "btn-red",
    45                         callback: function() {}
    46                     }
    47                 }
    48             });
    49         }
    50     }
    51 }
    52 
    53 /**
    54  * Función para cargar preguntas luego de un error en el formulario
    55 **/
    56 function cargar_preguntas() {
    57     $.each(opciones,function(){
    58         $('#agregar_preguntas').append($('#preguntas').html());   
    59     });
    60     $.each($('#agregar_preguntas #id_texto_pregunta_modal'),function(key,value){
    61         $(value).val(opciones[key]['texto_pregunta']);
    62     });
    63     $.each($('#agregar_preguntas #id_tipo_pregunta_modal'),function(key,value){
    64         $(value).val(opciones[key]['tipo_pregunta']).change();
    65     });
    66 }
    67 
    68 /**
    69  * Función para agregar opciones si la pregunta lo requiere
    70  * @param element Recibe el elemento de la consulta
    71 **/
    72 function add_option(element) {
    73     var option = $(element).parent().parent().parent().find('#for_options');
    74     $(option).append($('#agregar_opciones').html());
    75 }
    76 
    77 /**
    78  * Función para agregar opciones si la pregunta lo requiere
    79  * @param element Recibe el id de la consulta
    80 **/
    81 function remove_option(element) {
    82     $(element).parent().parent().parent().remove();
    83 }
    84 
    85 /**
    86  * Función para mostrar las preguntas de una consulta
    87  * @param id Recibe el id de la consulta
    88 **/
    89 function ver_preguntas(id) {
    90     $.ajax({
    91         type: 'GET',
    92         url: "/administrador/consulta/ajax/pregunta-list/"+id,
    93         success: function(response) {
    94             if (response.success) {
    95                 var preguntas = response.preguntas;
    96                 var token = $('input').val();
    97                 var html = '<form action="" role="form" method="post" id="question_form">';
    98                 html += '<input type="hidden" name="csrfmiddlewaretoken" value="'+token+'">';
    99                 $.each(preguntas,function(key,value){
    100                     html += "<h4>Pregunta #"+parseInt(key+1)+"</h4>";
    101                     html+= $('#preguntas').html();
    102                     html += "<hr>";
    103                 });
    104                 html += "</form>";
    105                 bootbox.dialog({
    106                     message: html,
    107                     title: "Preguntas",
    108                     buttons: {
    109                         success: {
    110                             label: "Guardar",
    111                             className: "btn-primary",
    112                             callback: function() {
    113                                 update_question();
    114                             }
    115                         },
    116                         close: {
    117                             label: "Cerrar",
    118                             className: "btn-red",
    119                             callback: function() {}
    120                         }
    121                     }
    122                 });
    123                 $.each($('.bootbox-body #id_texto_pregunta_modal'),function(key,value){
    124                     $(value).val(preguntas[key]['texto_pregunta']);
    125                     $(value).append('<input type="hidden" name="texto_pregunta_id" value="'+preguntas[key]['id']+'">');
    126                 });
    127                 $.each($('.bootbox-body select'),function(key,value){
    128                     $(value).val(preguntas[key]['tipo_pregunta']).change();
    129                     if (preguntas[key]['tipo_pregunta']<=2) {
    130                         var padre = $(value).parent().parent().parent().parent()
    131                         var agregar_opciones = $(padre).find("#add_options");
    132                         html = '<h5 class="text-success">Agregar opción '
    133                         html += '<a href="#" onclick="agregar_opcion('+preguntas[key]['id']+')">';
    134                         html += '<span class="glyphicon glyphicon-plus text-success"></span></a></h5>';
    135                         $(agregar_opciones).append(html);
    136                         html = '<div class="col-sm-12"><h5 class="text-info">Ver opciones '
    137                         html += '<a href="#" onclick="see_option('+preguntas[key]['id']+')">';
    138                         html += '<span class="glyphicon glyphicon-plus text-info"></span></a></h5></div>';
    139                         $(padre).append(html);
    140                     }
    141                 });
    142                 $.each($('.bootbox-body h4 a'),function(key,value){
    143                     $(value).attr('onclick','del_pregunta(this,'+preguntas[key]['id']+')');
    144                 });
    145             }
    146             else{
    147                
    148             }
    149         },
    150         error:function(error)
    151         {
    152             bootbox.alert("Ocurrió un error inesperado");
    153         }
    154     });
    155 }
    156 
    157 /**
    158  * Función para abrir el formulario de opciones
    159  * @param id Recibe el id de la pregunta
    160 **/
    161 function agregar_opcion(id) {
    162     bootbox.dialog({
    163         message: $('#formulario').html(),
    164         title: "Opciones",
    165         buttons: {
    166             success: {
    167                 label: "Guardar",
    168                 className: "btn-primary",
    169                 callback: function() {
    170                     submitOption(this);
    171                 }
    172             },
    173             close: {
    174                 label: "Cerrar",
    175                 className: "btn-red",
    176                 callback: function() {}
    177             }
    178         }
    179     });
    180     $('#formulario_modal').append($('#agregar_opciones_base').html());
    181     $('#formulario_modal').attr('action',id);
    182 }
    183 
    184 /**
    185  * Función para enviar el formulario de las opciones
    186 **/
    187 function submitOption(objecto) {
    188     var form = $(objecto).find('form');
    189     $.ajax({
    190         data: $(form).serialize(),
    191         type: 'POST',
    192         url: '/administrador/consulta/create-option/'+$(form).attr('action'),
    193         success: function(response) {
    194             if (response.code) {
    195                 bootbox.alert("Se crearon las opciones con éxito");
    196             }
    197             else{
    198                 var errors = '';
    199                 $.each(response.errors,function(key,value){
    200                     errors += key+" "+value+"<br>";
    201                 });
    202                 bootbox.alert(errors);
    203             }
    204         }
    205     });
    206 }
    207 
    208 /**
    209  * Función para ver las opciones de un pregunta
    210  * @param id Recibe el id de la pregunta
    211 **/
    212 function see_option(id) {
    213     $.ajax({
    214     type: 'GET',
    215     url: "/administrador/consulta/ajax/opciones-list/"+id,
    216     success: function(response) {
    217         if (response.success) {
    218             var opciones = response.opciones;
    219             var token = $('input').val();
    220             var html = '<form action="" role="form" method="post" id="option_form">';
    221             html += '<input type="hidden" name="csrfmiddlewaretoken" value="'+token+'">';
    222             $.each(opciones,function(key,value){
    223                 html += "<h4>Opcion #"+parseInt(key+1)+"</h4>";
    224                 html+= $('#agregar_opciones').html();
    225                 html += "<hr>";
    226             });
    227             html+= '</form>';
    228             bootbox.dialog({
    229                 message: html,
    230                 title: "Opciones",
    231                 buttons: {
    232                     success: {
    233                         label: "Guardar",
    234                         className: "btn-primary",
    235                         callback: function() {
    236                             update_option(id);
    237                         }
    238                     },
    239                     close: {
    240                         label: "Cerrar",
    241                         className: "btn-red",
    242                         callback: function() {}
    243                     }
    244                 }
    245             });
    246             $.each($('.bootbox-body #option_form #id_texto_opcion'),function(key,value){
    247                 $(value).val(opciones[key]['texto_opcion']);
    248                 $(value).append('<input type="hidden" name="texto_opcion_id" value="'+opciones[key]['id']+'">');
    249             });
    250             $.each($('.bootbox-body #option_form #opciones a'),function(key,value){
    251                 $(value).attr('onclick','del_option(this,'+opciones[key]['id']+')');
    252             });
    253             }
    254         },
    255         error:function(error)
    256         {
    257             bootbox.alert("Ocurrió un error inesperado");
    258         }
    259     });
    260 }
    261 
    262 /**
    263  * Función para actualizar las opciones de un pregunta
    264  * @param id Recibe el id de la pregunta
    265 **/
    266 function update_option(id) {
    267     var form = $("#option_form");
    268     $.ajax({
    269         data: $(form).serialize(),
    270         type: 'POST',
    271         url: '/administrador/consulta/update-option',
    272         success: function(response) {
    273             if (response.code) {
    274                 bootbox.alert("Se actualizaron las opciones con éxito");
    275             }
    276             else{
    277                 var errors = '';
    278                 $.each(response.errors,function(key,value){
    279                     errors += key+" "+value+"<br>";
    280                 });
    281                 bootbox.alert(errors);
    282             }
    283         }
    284     });
    285 }
    286 
    287 /**
    288  * Función para eliminar las opciones de un pregunta
    289  * @param id Recibe el id de la pregunta
    290 **/
    291 function del_option(element,id) {
    292         bootbox.dialog({
    293         message: "¿Desea borrar la opción seleccionada?",
    294         title: "Alerta",
    295         buttons: {
    296             success: {
    297                 label: "Si",
    298                 className: "btn-primary",
    299                 callback: function() {
    300                     var token = $('input').val();
    301                     $.ajax({
    302                         data: {'csrfmiddlewaretoken':token},
    303                         type: 'POST',
    304                         url: '/administrador/consulta/delete-option/'+id,
    305                         success: function(response) {
    306                             if (response.success) {
    307                                 remove_option(element);
    308                                 bootbox.alert("Se eliminó la opción con éxito");
    309                             }
    310                             else {
    311                                 bootbox.alert(response.mensaje);
    312                             }
    313                         },
    314                         error:function(error)
    315                         {
    316                             bootbox.alert("Ocurrió un error inesperado");
    317                         }
    318                     });
    319                 }
    320             },
    321             close: {
    322                 label: "No",
    323                 className: "btn-red",
    324                 callback: function() {}
    325             }
    326         }
    327     });
    328 }
    329 
    330 /**
    331  * Función para eliminar una pregunta
    332  * @param id Recibe el id de la pregunta
    333 **/
    334 function del_pregunta(element,id) {
    335         bootbox.dialog({
    336         message: "¿Desea borrar la pregunta seleccionada?",
    337         title: "Alerta",
    338         buttons: {
    339             success: {
    340                 label: "Si",
    341                 className: "btn-primary",
    342                 callback: function() {
    343                     var token = $('input').val();
    344                     $.ajax({
    345                         data: {'csrfmiddlewaretoken':token},
    346                         type: 'POST',
    347                         url: '/administrador/consulta/delete-question/'+id,
    348                         success: function(response) {
    349                             if (response.success) {
    350                                 remove_option(element);
    351                                 bootbox.alert("Se eliminó la pregunta con éxito");
    352                             }
    353                             else {
    354                                 bootbox.alert(response.mensaje);
    355                             }
    356                         },
    357                         error:function(error)
    358                         {
    359                             bootbox.alert("Ocurrió un error inesperado");
    360                         }
    361                     });
    362                 }
    363             },
    364             close: {
    365                 label: "No",
    366                 className: "btn-red",
    367                 callback: function() {}
    368             }
    369         }
    370     });
    371 }
    372 
    373 /**
    374  * Función para abrir el formulario de preguntas
    375  * @param id Recibe el id de la consulta
    376 **/
    377 function add_preguntas(id) {
    378     var token = $('input').val();
    379     var html = '<form action="" role="form" method="post" id="question_form">';
    380     html += '<input type="hidden" name="csrfmiddlewaretoken" value="'+token+'">';
    381     html += '<div class="content"><h5 class="text-success">Agregar Preguntas '
    382     html += '<a href="#" onclick="agregar_preguntas(\'#preguntas_base\');">';
    383     html += '<span class="glyphicon glyphicon-plus text-success"></span></a></h5></div>';
    384     html += '<div id="agregar_preguntas">';
    385     html += $('#preguntas_base').html();
    386     html += '</div></form>';
    387     bootbox.dialog({
    388         message: html,
    389         title: "Preguntas",
    390         buttons: {
    391             success: {
    392                 label: "Guardar",
    393                 className: "btn-primary submit-question",
    394                 callback: function() {
    395                     var vacio = false;
    396                     $.each($('.modal-body #id_texto_pregunta'),function(key,value){
    397                         if ($(value).val().trim()=='') {
    398                             vacio = true;
    399                         }
    400                     });
    401                     $.each($('.modal-body #id_tipo_pregunta'),function(key,value){
    402                         if ($(value).val().trim()=='') {
    403                             vacio = true;
    404                         }
    405                     });
    406                     if (vacio) {
    407                         event.preventDefault();
    408                         bootbox.dialog({
    409                             message: "Debe llenar todas las preguntas que agregó",
    410                             title: "<b class='text-danger'>Error</b>",
    411                             buttons: {
    412                                 success: {
    413                                     label: "Cerrar",
    414                                     className: "btn-red",
    415                                     callback: function() {}
    416                                 }
    417                             }
    418                         });
    419                     }
    420                     else{
    421                         create_question(id);
    422                     }
    423                 }
    424             },
    425             close: {
    426                 label: "Cerrar",
    427                 className: "btn-red",
    428                 callback: function() {}
    429             }
    430         }
    431     });
    432 }
    433 
    434 /**
    435  * Función para crear un pregunta
    436  * @param id Recibe el id de la consulta
    437 **/
    438 function create_question(id) {
    439     var form = $("#question_form");
    440     $.ajax({
    441     type: 'POST',
    442     data: $(form).serialize(),
    443     url: "/administrador/consulta/create-question/"+id,
    444     success: function(response) {
    445         if (response.code) {
    446             bootbox.alert("Se crearon/creó la(s) pregunta(s) con éxito");
    447         }
    448         else{
    449             var errors = '';
    450             $.each(response.errors,function(key,value){
    451                 errors += key+" "+value+"<br>";
    452             });
    453             bootbox.alert(errors);
    454         }
    455     },
    456         error:function(error)
    457         {
    458             bootbox.alert("Ocurrió un error inesperado");
    459         }
    460     });
    461 }
    462 
    463 /**
    464  * Función para actualizar las preguntas de una consulta
    465 **/
    466 function update_question() {
    467     var form = $("#question_form");
    468     $.ajax({
    469         data: $(form).serialize(),
    470         type: 'POST',
    471         url: '/administrador/consulta/update-question',
    472         success: function(response) {
    473             if (response.code) {
    474                 bootbox.alert("Se actualizaron las preguntas con éxito");
    475             }
    476             else{
    477                 var errors = '';
    478                 $.each(response.errors,function(key,value){
    479                     errors += key+" "+value+"<br>";
    480                 });
    481                 bootbox.alert(errors);
    482             }
    483         },
    484         error:function(error)
    485         {
    486             bootbox.alert("Ocurrió un error inesperado");
    487         }
    488     });
    489 }
    490 
    4911/**
    4922 * Función para enviar los respuestas de la encuesta
     
    55262        })
    55363    .fail(function(response){
    554         bootbox.alert("Ocurrió un error inesperado");
     64        MaterialDialog.alert("Ocurrió un error inesperado",{
     65            'title':"Error",
     66            'buttons':{'close':{'text':'cerrar'}}
     67        });
    55568    });
    55669}
     
    652165    $(obj).val($(obj).val().replace("  ",""));
    653166}
     167
     168/**
     169 * @brief Función buscar los datos del municipio
     170 * @param valor Recibe el valor del select
     171 */
     172function get_municipio(valor) {
     173    if (valor!='') {
     174        var url = URL_BUSCAR_MUNICIPIO+'?entidad='+valor;
     175    }
     176    else{
     177        var url = URL_BUSCAR_MUNICIPIO;
     178        $('#id_municipio').attr('disabled',true);
     179        $('#id_municipio').material_select();
     180    }
     181    $.get(url)
     182        .done(function(response){
     183            $('#id_municipio').removeAttr('disabled');
     184            var html = json2html_select(response);
     185            $('#id_municipio').html(html);
     186            $('#id_municipio').material_select();
     187        })
     188        .fail(function(response){
     189            MaterialDialog.alert("Ocurrió un error inesperado",{
     190                'title':"Error",
     191                'buttons':{'close':{'text':'cerrar'}}
     192            });
     193        });
     194}
     195
     196/**
     197 * @brief Función buscar los datos de la parroquia
     198 * @param valor Recibe el valor del select
     199 */
     200function get_parroquia(valor) {
     201    if (valor!='') {
     202        var url = URL_BUSCAR_PARROQUIA+'?municipio='+valor;
     203    }
     204    else{
     205        var url = URL_BUSCAR_PARROQUIA;
     206        $('#id_parroquia').attr('disabled',true);
     207        $('#id_parroquia').material_select();
     208    }
     209    $.get(url)
     210        .done(function(response){
     211            $('#id_parroquia').removeAttr('disabled');
     212            var html = json2html_select(response);
     213            $('#id_parroquia').html(html);
     214            $('#id_parroquia').material_select();
     215        })
     216        .fail(function(response){
     217            MaterialDialog.alert("Ocurrió un error inesperado",{
     218                'title':"Error",
     219                'buttons':{'close':{'text':'cerrar'}}
     220            });
     221        });
     222}
     223
     224/**
     225 * @brief Función para convertir el json del select en el html correspondiente
     226 * @param data Recibe los valores en formato JSON
     227 * @return html Retorna los datos transformados en HTML
     228 */
     229function json2html_select(data) {
     230    var html = '';
     231    $.each(data,function(key,value){
     232        html += '<option value="'+value[0]+'">'+value[1]+'</option>';
     233    });
     234    return html;
     235}
  • users/forms.py

    rd923030 r3625c13  
    124124        if 'estado' in self.data and self.data['estado']:
    125125            self.fields['municipio'].widget.attrs.pop('disabled')
    126             self.fields['municipio'].queryset=Municipio.objects.filter(entidad=self.data['estado'])
     126            self.fields['municipio'].queryset = cargar_municipios(self.data['estado'])
    127127
    128128            # Si se ha seleccionado un municipio establece el listado de parroquias y elimina el atributo disable
    129129            if 'municipio' in self.data and self.data['municipio']:
    130130                self.fields['parroquia'].widget.attrs.pop('disabled')
    131                 self.fields['parroquia'].queryset=Parroquia.objects.filter(municipio=self.data['municipio'])
    132        
    133         if 'participacion' in self.data and self.data['participacion']=='CO':
    134             self.fields['colectivo'].widget.attrs.pop('readonly')
     131                self.fields['parroquia'].queryset = cargar_parroquias(self.data['municipio'])
    135132       
    136133        self.fields['estado'].choices = cargar_entidad()
     
    178175    cedula = CedulaField()
    179176   
    180     ## sector
    181     sector = forms.ChoiceField(
    182         widget=forms.Select(attrs={'class': 'form-control input-md','onchange':'mostrar_sector(this.value);'}),
    183         label="Sector",choices=(('','Seleccione...'),)+SECTORES
    184         )
    185177   
    186178    ## estado
    187179    estado = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control input-md',
    188         'onchange': "actualizar_combo(this.value,'base','Municipio','entidad','codigo','nombre','id_municipio')"}))
     180        'onchange': "get_municipio(this.value)"}))
    189181   
    190182    ## municipio
    191183    municipio = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control input-md','disabled':'disabled',
    192         'onchange': "actualizar_combo(this.value,'base','Parroquia','municipio','codigo','nombre','id_parroquia')"}))
     184        'onchange': "get_parroquia(this.value)"}))
    193185   
    194186    ## parroquia
     
    242234        if(validate_email(email)):
    243235            raise forms.ValidationError("El correo ingresado ya existe")
    244         return email
    245    
    246    
    247     def clean_sector_trabajador(self):
    248         """!
    249         Método que valida el sector trabajador
    250    
    251         @author Rodrigo Boet (rboet at cenditel.gob.ve)
    252         @copyright GNU/GPLv2
    253         @date 24-05-2017
    254         @param self <b>{object}</b> Objeto que instancia la clase
    255         @return Retorna el campo con la validacion
    256         """
    257         sector = self.cleaned_data['sector']
    258         sector_trabajador = self.cleaned_data['sector_trabajador']
    259         if(sector=='TR' and sector_trabajador==''):
    260             raise forms.ValidationError("Debe ingresar el sector dónde trabaja")
    261         return sector_trabajador
    262    
    263     def clean_sector_estudiante(self):
    264         """!
    265         Método que valida el sector estudiante
    266    
    267         @author Rodrigo Boet (rboet at cenditel.gob.ve)
    268         @copyright GNU/GPLv2
    269         @date 24-05-2017
    270         @param self <b>{object}</b> Objeto que instancia la clase
    271         @return Retorna el campo con la validacion
    272         """
    273         sector = self.cleaned_data['sector']
    274         sector_estudiante = self.cleaned_data['sector_estudiante']
    275         if(sector=='ES' and sector_estudiante==''):
    276             raise forms.ValidationError("Debe ingresar el sector dónde estudia")
    277         return sector_estudiante
    278        
     236        return email       
    279237       
    280238    class Meta:
  • users/views.py

    r810b149 r3625c13  
    102102    success_url = reverse_lazy('login')
    103103    success_message = "Se registró con éxito"
    104     model = User
    105104
    106105    def form_valid(self, form, **kwargs):
Nota: Vea TracChangeset para ayuda en el uso del visor de conjuntos de cambios.