问题
I'm trying to display data into the modal body with django variables. I'm very noob at ajax and django. The ajax function passes the id of the Galeria object and then the view returns a JsonResponse with the data. Why the modal is not taking the data? If I console.log it prints the data as well, but when I try to pass the data via django variables, the modal shows empty. What am I doing wrong?
My views.py
def get_galeria(request):
galeria = Galeria.objects.get(id=int(request.GET['ajax_galeria']))
print(galeria.id)
context = {}
context['galeriaID'] = galeria.id
context['galeriaNombre'] = galeria.nombre
return JsonResponse(context, safe=False)
models.py
class Galeria(models.Model):
uuid = models.CharField(unique=True, max_length=36, blank=True, null=True)
usuario_creador = models.ForeignKey('Usuario', on_delete=models.CASCADE, db_column='usuario_creador', blank=True, null=True, related_name='galerias_usuariocreador')
usuario_auditor = models.ForeignKey('Usuario', on_delete=models.CASCADE, db_column='usuario_auditor', blank=True, null=True, related_name='galerias_usuarioauditor')
nombre = models.CharField(unique=True, max_length=100)
ruta = models.ImageField(upload_to=settings.MEDIA_ROOT, unique=True, max_length=255)
es_imagen = models.IntegerField()
es_video = models.IntegerField()
es_audio = models.IntegerField(blank=True, null=True)
auditada = models.DateTimeField(blank=True, null=True)
descripcion = models.TextField(blank=True, null=True)
modificado = models.DateTimeField(blank=True, null=True)
eliminado = models.IntegerField(blank=True, null=True)
tipo = models.CharField(max_length=10, blank=True, null=True)
grupo = models.ForeignKey('Grupo', on_delete=models.CASCADE, db_column='grupo', blank=True, null=True, related_name='galerias_grupo')
fecha_creacion = models.DateField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.nombre
class Meta:
managed = True
db_table = 'galeria'
index.html (see ajax function and modal with id='modal_info_galeria')
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Local CSS -->
<link rel="stylesheet" href="/static/css/style.css">
<!-- Material Icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Google Fonts -->
<!-- <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet"> -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,400i,500,500i,700&display=swap" rel="stylesheet">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<section class="contenedor" id="sidemenutrans">
<!-- Header Grid -->
<div class="header-bar">
<!-- Header Title -->
<div class="title-section">
Galeria de Medios
</div>
<!-- Header Navbar -->
<nav class="navbar navbar-expand-lg navbar-light navbar-edited">
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<i class="material-icons" style="font-size:30px;cursor:pointer" onclick="openNav()">
menu
</i>
<!-- Sidebar Menu -->
<div id="mySidenav" class="sidenav">
<div class="profile-cont">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="profile-img"></a></div>
<div class="username">{{ user }}</div>
<div class="profile-bg"></div>
</div>
<!-- Items, secciones administrativas links -->
<section class="menu-section">
<a href="{% url 'index' %}" class="menu-option"><i class="material-icons icon-menu">insert_photo</i> Galeria</a>
<a href="{% url 'pantallas' %}" class="menu-option"><i class="material-icons icon-menu">personal_video</i>Pantallas</a>
</section>
</div>
<!-- Header - Navbar Content -->
<ul class="navbar-nav mr-auto">
<li class="nav-item dropdown">
<!-- Split dropright button -->
<div class="btn-group dropright">
<button type="submit" form='form_filter_galerias' class="btn btn-secondary">
FILTRAR
</button>
<button type="button" class="btn btn-secondary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropright</span>
</button>
<!--DROPDOWN FILTROS-->
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<!--FORMULARIO DE FILTROS-->
<form action='{% url "filtrar_galerias" %}' method='POST' id='form_filter_galerias'>
{% csrf_token %}
<h6 class="dropdown-header">Tipos de Archivo</h6>
<div class="form-check; dropdown-item">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="filter_tipoarchivo" value='Imagenes' checked>Imagenes
</label>
</div>
<div class="form-check; dropdown-item">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="filter_tipoarchivo" value='Videos'>Videos
</label>
</div>
<div class="form-check disabled; dropdown-item">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="filter_tipoarchivo" value='Audios' disabled>Audios
</label>
</div>
<!--SEPARADOR DROPDOWN-->
<div class="dropdown-divider"></div>
<h6 class="dropdown-header">Filtrar por:</h6>
<div class="form-check; dropdown-item">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="filter_otros" value='Autor'>Autor
</label>
</div>
<div class="form-check; dropdown-item">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="filter_otros" value='Fecha_asc'>Fecha ASC
</label>
</div>
<div class="form-check; dropdown-item">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="filter_otros" value='Fecha_desc'>Fecha DESC
</label>
</div>
<div class="form-check; dropdown-item">
<label class="form-check-label">
<input type="text" class="col-12 form-check-input" name="filter_grupo" placeholder="Grupo...">
</label>
</div>
</form>
</div>
</div>
</li>
<!-- Button Subir Archivo (Modal) -->
<li style='padding-left: 5px;'>
<button type="button" class="btn btn-primary" id="UploadButton" data-toggle="modal"
data-target="#staticBackdrop">Subir Archivo</button>
</li>
</ul>
<!-- Formulario de Busqueda de Galerias -->
<form class="form-inline my-2 my-lg-0" action='{% url "buscar_galerias" %}' method='GET'>
<input class="form-control mr-sm-2" type="search" placeholder="Buscar galerias" aria-label="Search" name='search'>
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button>
</form>
</div>
</nav>
</div>
<!-- Modal Subir Archivo -->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<!-- Modal Subir Archivo - Header -->
<div class="modal-header border-0">
<h5 class="modal-title" id="staticBackdropLabel">Subir Contenido</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- Modal Subir Archivo - Drag & Drop Body -->
<div class="modal-body dad-container">
<div class="caption-info">
<i class="material-icons md-48 caption-sign">add</i>
<p class="caption-text">Drag & Drop Files Here</p>
</div>
</div>
<!-- Modal Subir Archivo - Footer Browser -->
<div class="modal-footer border-0 footer-edited">
<!-- FORMULARIO CREAR GALERIA -->
<form method='POST' enctype="multipart/form-data" action='{% url "crear_galeria" %}'>
{% csrf_token %}
<div class="custom-file">
<input type="file" class="custom-file-input browse-file" id="customFile" name='Galeria_ruta' required>
<label class="custom-file-label" for="customFile">Elegir archivo...</label>
</div>
<button type="submit" class="btn btn-outline-success">Subir Archivo</button>
</form>
</div>
</div>
</div>
</div>
<!-- Media Content Container -->
<div class="content">
<!-- Recorrer las galerias -->
{% for g in galerias %}
<!-- Si la galeria es imagen, crear container de imagen -->
{% if g.es_imagen == 1 %}
<!-- Container de Imagen -->
<div class="img-container">
<img id="img-content" src="{{g.ruta.url}}">
<p>{{galeriaID}}</p>
<!-- Formulario para Borrar Galeria Imagen -->
<form method='POST' action='{% url "borrar_galeria" %}' id='form_borrar_galeria'>
{% csrf_token %}
</form>
<!-- Formulario para Obtener la Galeria (para ser usada en una modal)-->
<form id='form_get_galeria'>
{% csrf_token %}
</form>
<input type="radio" class="form-check-input" name="selected_galeria" id='selected_galeria' form='form_borrar_galeria' value="{{g.id}}">
</div>
<!-- Si la galeria es video, crear container de video -->
{% elif g.es_video == 1 %}
<div class="img-container">
<!-- Container de Video -->
<video id='img-content' controls>
<source src="{{g.ruta.url}}" type="video/mp4" media="screen and (min-width:320px)">
<source src="{{g.ruta.url}}" type="video/ogg" media="screen and (min-width:320px)">
<source src="{{g.ruta.url}}" type="video/avi" media="screen and (min-width:320px)">
<source src="{{g.ruta.url}}" type="video/wav" media="screen and (min-width:320px)">
<source src="{{g.ruta.url}}" type="video/mkv" media="screen and (min-width:320px)">
<source src="{{g.ruta.url}}" type="video/ogg" media="screen and (min-width:320px)">
Su navegador no soporta contenido multimedia.
</video>
<!-- Formulario para Borrar Galeria Video -->
<form method='POST' action='{% url "borrar_galeria" %}' id='form_borrar_galeria'>
{% csrf_token %}
</form>
<!-- Formulario para Obtener la Galeria (para ser usada en una modal)-->
<form id='form_get_galeria'>
{% csrf_token %}
</form>
<input type="radio" class="form-check-input" name="selected_galeria" form='form_borrar_galeria' value="{{g.id}}">
</div>
{% endif %}
<!-- Si no hay galerias, imprimir este tag -->
{% empty %}
<h1 style='color:red'>No hay galerias disponibles. Presione Subir Archivo para agregar una galeria.</h1>
{% endfor %}
</div>
<div class="modal fade" id="modal_galeria_info" tabindex="-1" role="dialog" aria-labelledby="modal_galeria_infoLabel" aria-hidden="true" style='display: none;'>
<div class="modal-dialog" role="document" id='datos'>
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal_galeria_infoLabel">Detalles de la Galeria</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id='modal_galeria_body'>
<p>{{galeriaNombre}} {{galeriaID}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- Media Content Container - Delete Galeria Button -->
<button type="submit" class="btn btn-danger delete-btn" form='form_borrar_galeria'>
<i class="material-icons">delete</i>
</button>
<button type="submit" id='info_btn_galeria' class="btn btn-info info-btn" form='form_get_galeria' onclick="get_galeria_details()" data-toggle="modal" data-target="#modal_galeria_info">
<i class="material-icons">info</i>
</button>
<div id='modal-div' name='modal-div'></div>
</section>
<!-- Off Canvas Menu Java Script -->
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("sidemenutrans").style.marginLeft = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("sidemenutrans").style.marginLeft = "0";
}
</script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
crossorigin="anonymous"></script>
<script>
// Submit post on submit
$('#form_get_galeria').on('submit', function(event){
event.preventDefault();
//get_galeria_details();
});
// AJAX for posting
function get_galeria_details() {
console.log('get galeria details function running');
$.ajax({
url : "{% url 'obtener_galeria' %}", // the endpoint
type : "GET", // http method
//dataType: "json",
//async: true,
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
ajax_galeria: $("input[type=radio][name=selected_galeria]:checked").val()
}, // data sent with the post request
// handle a successful response
success : function(data, response) {
//$('#selected_galeria').val(''); // remove the value from the input
console.log(data);
$(".modal-body").html(data);
document.getElementById('modal_galeria_info').style.display='block';
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
//$('#comment-form').prepend("<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>×</button>Oop! Error happend!</div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
</script>
</body>
</html>
回答1:
I solved my problem doing this in the ajax function:
from this:
// handle a successful response
success : function(data, response) {
//$('#selected_galeria').val(''); // remove the value from the input
console.log(data);
$(".modal-body").html(data);
document.getElementById('modal_galeria_info').style.display='block';
},
To this:
// handle a successful response
success : function(data, response) {
//$('#selected_galeria').val(''); // remove the value from the input
console.log(data.galeriaID);
document.getElementById('gg').innerHTML = data.galeriaID;
},
It was really obvious and I can't believe I'm a fool. I was trying to paste html with the data, instead of passing data to the elements.
Problem Solved.
来源:https://stackoverflow.com/questions/59625095/why-bootstrap4-modal-doesnt-show-data-in-my-django-template