Removing bootstrap Modal from DOM - javascript

I am working on a piece of code to load part of my content dynamically after user triggers the event by clicking.
Case Scenario is: when user clicks on the post, it will open a modal and display the detailed view which is the dynamic generated content using the slug in the link. However, I need to remove the modal from the DOM when user closes the modal. for now i have only been able to hide it but I need to remove it.
here is my code.
PHP Laravel HTML Markup ():
<div class="content-blocks blog hidex">
<section class="content">
<div class="block-content">
<h3 class="block-title">My Blog</h3>
<div id="post-list" class="col-md-10 col-md-offset-1">
{% set posts = blogPosts.posts %}
{% for post in posts %}
<div class="post">
<div class="post-thumbnail">
{% if post.featured_images.count %}
{% set image = post.featured_images|first %}
<a class="open-post" href="{{'blog-post'|page}}">
<img
data-src="{{ image.filename }}"
src="{{ image.path }}"
alt="{{ image.description }}"
style="max-width: 100%"/>
</a>
{% endif %}
</div>
<div class="post-title">
<a class="open-post" href="{{ post.url }}"><h2>{{ post.title }}</h2></a>
<p class="post-info">
<span class="post-author">Posted by {{ post.user.first_name}} </span>
<span class="slash"></span>
<span class="post-date">on {{ post.published_at|date('M d, Y') }}</span>
<span class="slash"></span>
{% if post.categories.count %} in {% endif %}
{% for category in post.categories %}
<span class="post-category">{{ category.name }}</span>
{% if not loop.last %}, {% endif %}
{% endfor %}
</p>
</div>
<div class="post-body">
<p>{{ post.summary }}</p>
<a class="btn open-post" href="{{ post.url }}">Read More</a>
</div>
</div>
{% endfor %}
<div class="text-center">
{% if posts.lastPage > 1 %}
<ul class="pagination">
{% if posts.currentPage > 1 %}
<li>
<a href="{{ this.page.baseFileName|page({ (pageParam): (posts.currentPage-1) }) }}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a></li>
{% endif %}
{% for page in 1..posts.lastPage %}
<li class="{{ posts.currentPage == page ? 'active' : null }}">
{{ page }}
</li>
{% endfor %}
{% if posts.lastPage > posts.currentPage %}
<li><a href="{{ this.page.baseFileName|page({ (pageParam): (posts.currentPage+1) }) }}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</section>
</div>
JavaScript:
//Blog post Modal
$('.open-post').on('click', function(){
var postUrl = $(this).attr("href");
var post = '<div class="modal" id="post-modal"><div class="inline-menu-container"><a id="modal-close" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></a></div><div class="modal-dialog"><div class="modal-content"></div></div></div>';
$(post).modal({
remote: postUrl
})
return false;
});
// close the modal
$('#close').on( 'click', function() {
$('.name-block').removeClass('reverse');
$('.name-block-container').removeClass('reverse');
$('.menu-blocks').removeClass('hidex');
$('.content-blocks').removeClass('showx');
$('.content-blocks').addClass('hidex');
$('.inline-menu-container').removeClass('showx');
$('.inline-menu-container').addClass('hidex');
$('.menu-item').removeClass('active');
});
result of Javascript code in the DOM:
<div class="modal in" id="post-modal" style="display: block; padding-left: 0px;">
<div class="inline-menu-container">
<a id="modal-close" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></a>
</div>
<div class="modal-dialog">
<div class="modal-content">
/// all the dynamic content in the modal
</div>
</div>
Now I need to remove this result without refreshing the page.
Update:
This is how it looks in the HTML in Inspect after closing the modal:
Note:
I tried to remove the modal content from the DOM using the #post-modal id but wasn't successful. also, i haven't been able to find an example of using Delegate while the modal elements and content are completely added by javascript after loading the 'DOM'.

Bind an event and then remove().
$('.modal').on('hidden.bs.modal', function () {
$(this).remove();
});
or
$('.modal').on('hidden.bs.modal', function () {
$('.modal').remove();
});

Thanks to I.G. Pascual and Serg Chernata here is the solution:
Javascript code:
$(document).on('hidden.bs.modal', '.modal', function () { $("#post-modal").remove(); $(".modal-dialog").remove(); });

you can try this
$(modal).modal().on('hidden.bs.modal',function(e){
e.target.remove();
})
you can directly add the hidden event on the initialization itself. so you don't have to trigger separately each time.

Below given snippet will show you how can you do something that you want without having to do anything extra and also by not even writing conventional bootstrap modal code.
For further reference you can also visit this link. It will show you how you can create modal dynamically with minimum efforts.
function open_modal(name) {
var message = $('#frm_1');
BootstrapDialog.show({
title: 'New message to ' + name,
message: $('#frm_1'),
onshown: function() {
$('#recipient-name').val(name);
},
onhide: function(dialog) {
console.log('Cerrada');
$('#hidden-div').append(message);
},
buttons: [{
label: 'Close',
action: function(dialog) {
dialog.close();
}
}, {
label: 'Send message',
cssClass: 'btn btn-primary',
action: function(dialog) {
// Do whatever send message does, here
}
}]
});
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
<button type="button" class="btn btn-primary" onclick="open_modal('#mdo')">Open modal for #mdo</button>
<button type="button" class="btn btn-primary" onclick="open_modal('#fat')">Open modal for #fat</button>
<button type="button" class="btn btn-primary" onclick="open_modal('#getbootstrap')">Open modal for #getbootstrap</button>
<div id="hidden-div" style="display : none">
<form id="frm_1">
<div class="form-group">
<label for="recipient-name" class="control-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>

Related

Twitter-Bootstrap 5 carousel indicators and controls not working. Why?

I am making a ecommerce website with Django framework.
I cannot make my bootstrap carousel work. Clicking on indicators and controls has no effect.
I have pulled in Bootstrap source files with NPM.
main.html
<!DOCTYPE html>
{% load static %}
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{% static 'css/main.css' %}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>
{% block title %}
{% endblock title %}
</title>
</head>
<body class="mt-sm-5 mt-md-5 mt-lg-5 mt-xl-5">
<header>
<div class="container border-bottom border-primary border-1">
</div>
</header>
<section class="page-content" id="page-content">
{% block content %}
{% endblock content %}
</section>
<script src="{% static 'js/bootstrap.js' %}"></script>
</body>
</html>
product_details.html
{% extends 'main.html' %}
{% load static %}
{% block title %}
Boutique - {{ product.title }}
{% endblock title %}
{% block content %}
<div class="container">
<div class="row" >
<div id="product-carousel" class="col-sm-12 col-md-6 border border-danger carousel slide carousel-fade" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#product-carousel" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
{% if product.image2 %}
<button type="button" data-bs-target="#product-carousel" data-bs-slide-to="1" aria-label="Slide 2"></button>
{% endif %}
{% if product.image3 %}
<button type="button" data-bs-target="#product-carousel" data-bs-slide-to="2" aria-label="Slide 3"></button>
{% endif %}
</div>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{{ product.image.url }}" class="img-fluid" alt="...">
</div>
{% if product.image2 %}
<div class="carousel-item">
<img src="{{ product.image2.url }}" class="img-fluid" alt="...">
</div>
{% endif %}
{% if product.image3 %}
<div class="carousel-item">
<img src="{{ product.image3.url }}" class="img-fluid" alt="...">
</div>
{% endif %}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#product-carousel" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#product-carousel" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="col-sm-12 col-md-6 border border-warning">
<h3> {{ product.title }} </h3>
<h4> {{ product.price }} € </h4>
<h5> {{ product.description }} </h5>
<h6> {{ product.category }} </h6>
{% if product.stock > 0 %}
<div class="container border border-success">
<div class="row" >
<div class="col">
<label for="select-qty">Quantity</label>
</div>
<div class="col">
<select class="form-select form-select-sm" aria-label=".form-select-sm example" id="select-qty">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div class="col">
<button id="add-to-cart-button" value="{{ product.id }}" type = "button" class="btn btn-success">Ajouter au panier</button>
</div>
</div>
</div>
{% endif %}
<div class="container">
<div class="row" >
<div class="col-sm-12 col-md-6">
<a class="btn btn-dark" href="{% url 'basket:basket_summary' %}">Panier</a>
</div>
<div class="col-sm-12 col-md-6">
<a class="btn btn-light" href="{% url 'store:all_products' %}">Voir les produits</a>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// Add to cart
$(document).on('click', '#add-to-cart-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "basket:basket_add" %}',
data: {
productid: $('#add-to-cart-button').val(),
productqty: $('#select-qty option:selected').val(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post',
},
success: function (json) {
document.getElementById("cart-count").innerHTML = json.qty;
},
error: function (xhr, errmsg, err) {
},
});
})
</script>
<script type="text/javascript">
$(function(){
$('#product-carousel').carousel();
});
</script>
{% endblock content %}
The products have at least to images (image and image 2) and the controls and indicators show. But nothing happens when clicking on them.
EDIT
In the browser console, I have two errors.
Uncaught SyntaxError: import declarations may only appear at top level of a module
Uncaught TypeError: $(...).carousel is not a function
You are getting an Uncaught TypeError: $(...).carousel is not a function because you called that function before you loading the boostrap.js.
Give this a try, first load the boostrap.js (you can load it from your local)
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
then add your custom script
<script type="text/javascript">
$(function(){
$('#product-carousel').carousel();
});
</script>

django template tag in static js files

I want to use template tag and variables in static js files.
I'll give you 3 files.
no1_ index.html
no2_ inc/index.html
no3_ index javascript file
no1 file is template. html tags in here.
and it refers to no2.file to include some scripts.
no2.file has some kinds of script includes.
and it refers to no3.file to make my own scripts.
in no3.file, I want to deal with my template variables from view.py
but at no3.file, It can not read template tags and variables.
what can I do for this issue?
no1_index.html
{% load static %}
{% load mathfilters %}
{% extends 'mobileWeb/base/base.html' %}
{% block content %}
{% include 'mobileWeb/inc/index/index.html' %}
<div id="map" style="width:80%;height:300px; margin:20px auto; border-radius: 10px;"></div>
<div style="width:90%; margin:auto">
<!-- this row will wrapping foreach-->
{% for mart in marts %}
<div class="row">
<div class="col-xs-5" onclick="martClick({{ mart }})">
{% with "/mobileWeb/images/"|add:mart.imageFileNo|add:".png" as path %}
<img src="{% static path %}" style="width:120px; height:120px; margin-top:10px;">
<br>
<h3>{{ mart.name }}</h3>
{% endwith %}
</div>
<div class="col-xs-7" style="height:200px; overflow:scroll" data-toggle="modal" data-target="#martModal"
data-whatever="{{ mart.id }}_{{ mart.name }}">
{% for item in items %}
{% if mart.id == item.mart %}
<div>
<h4 style="color:mediumpurple;">{{ item.name }}</h4>
{% if item.discountPrice == 1 or item.discountPrice == 100 %}
<h6><span
style="color:red">{{ item.originalPrice|sub:item.discountPrice|div:item.originalPrice|mul:100|floatformat:"0" }}% 할인</span>
</h6>
{% else %}
<h6>할인판매가 : {{ item.discountPrice }}원 <span
style="color:red">{{ item.originalPrice|sub:item.discountPrice|div:item.originalPrice|mul:100|floatformat:"0" }}% 할인</span>
</h6>
{% endif %}
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endfor %}
<!-- Mart Modal -->
<div class="modal fade" id="martModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="modal-title"></h4>
</div>
<div class="modal-body" id="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Item Modal -->
<div class="modal fade" id="itemModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="itemModal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="itemModal-title" id="itemModal-title" onclick="purchaseItem()"></h4>
</div>
<div class="itemModal-body" id="itemModal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onClick="stopTimer()">취소
</button>
</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
no2 inc/index.html
{% load static %}
<!-- outter module-->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-159115722-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-159115722-1');
</script>
<!-- kakao map -->
<script type="text/javascript"
src="//dapi.kakao.com/v2/maps/sdk.js?appkey=2a40b9e58744cbe7d0cb367e51c07eb4"></script>
<!-- css -->
<link rel="stylesheet" href="{% static 'mobileWeb/css/index/index.css' %}">
<!--js-->
{% block javascript %}
<script src="{% static 'mobileWeb/js/index/index.js' %}"></script>
{% endblock %}
no3 index javascript file
function writeMartModal(martId, martName) {
console.log("martID : " + martId);
document.getElementById('modal-body').innerHTML = '';
document.getElementById('modal-title').innerHTML = martName;
{% for item in items %}
var itemMartId = {{ item.mart }};
if (martId == itemMartId) {
var itemId = {{ item.id }};
var itemName = '{{ item.name }}';
var itemPrice = {{ item.discountPrice }};
var itemExpirationDate = '{{ item.expirationDate|date:"m월d일 H시 i분 까지" }}';
{% autoescape off %}
var itemComment = '{{ item.comment }}';
{% endautoescape %}
var html = "";
var div = document.createElement('div');
html += `
<div>
<div data-toggle="modal" data-target="#itemModal" data-whatever="${martName}_${itemId}_${itemName}">
<h4 style = "color:mediumpurple;" > ${itemName} </h4>
<h6> ${itemPrice}원 </h6>
<h6> ${itemExpirationDate} </h6>
</div>
{% autoescape off %}
<h6 style="color:red">${itemComment}</h6>
{% endautoescape %}
</div>
`
div.innerHTML = html;
document.getElementById('modal-body').appendChild(div);
}
{% endfor %}
};
errors in javascript file

How can I mark button as active based on the page I am at?

when a user clicks a tab I want that tab to show as active in blue. I can do it using if statements like the one I show on the code, but I would be repeating the code a LOT, so there has to be another way, could someone let me a hand please?
The current if statement shows the profile page which is active
<!-- This is saying: inherit everything from __base.html -->
{% extends "storePage/partials/__base.html" %}
<!-- Main base template which contains header and footer too -->
{% load crispy_forms_tags %}
<!-- To beautify the form at signup -->
{% block body %}
<div class="container bootstrap snippet">
<div class="row">
<div class="col-md-3">
<div class="list-group ">
<label class="card-header">Personal Settings</label>
{% if request.get_full_path == "/settings/profile/" %}
<span class="fa fa-user"></span> Profile
{% endif %}
<span class="fa fa-cog"></span> Account
<i class="fas fa-envelope"></i> Emails
<span class="fa fa-credit-card"></span> Billing
</div>
</div>
<!-- Center-right navBar-->
<div class="col-md-9">
{% block settingsPageInfo %} {% endblock %} <!-- Here goes the user information on the profile page -->
</div>
</div>
</div>
{% endblock %}
Here is a screenshot:
[]
How can I do it so when I go to Account it shows blue?
Thanks guys
Try to match your request URL name with your current URL, you can add active class like this or directly to the tag.
<ul>
<li class="{% if 'profile' in request.resolver_match.url_name %} active {% endif %}">
Profile
</li>
</ul>
This should solve your question:
<div class="container bootstrap snippet">
<div class="row">
<div class="col-md-3">
<div class="list-group ">
<label class="card-header">Personal Settings</label>
{% if request.get_full_path == "/settings/profile/" %}
<span class="fa fa-user"></span> Profile
{% endif %}
<span class="fa fa-cog"></span> Account
<i class="fas fa-envelope"></i> Emails
<span class="fa fa-credit-card"></span> Billing
</div>
</div>
<!-- Center-right navBar-->
<div class="col-md-9">
{% block settingsPageInfo %} {% endblock %} <!-- Here goes the user information on the profile page -->
</div>
</div>
create a common component like this
<angular-anchor-tag [url]="link1"></angular-anchor-tag>
angular-anchor-tag.html
<div>
<a href="url" class="link" (click)="highlightFunction($event)">
<div>
angular-anchor-tag.ts
#Input url;
highlightFunction(event){
//remove all the highlight classes from links
.$("link").removeClass("highlight");
add highlight class to the events target
event.target.addClass('highlight');
}

Jquery Countdown Plugin Not Working

I am using JQuery's countdown plugin in my Django application. I set up the countdown init script in a JQuery document.ready callback function, and I can see the javascript load when I check the network tab in Chrome's web inspector, but the plugin doesn't show up. I logged the element to the web console to make sure that it existed when I tried to call JQuery.countdown's .countDown method that kickstarts the plugin. It does in fact exist, but there is just empty space in between the tags. There are also no errors in the console.
Scripts "both JQuery and JQuery countdown being loaded"
<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type='text/javascript' src="/static/js/menu.js"></script>
<script type='text/javascript' src="/static/js/user_actions.js"></script>
<script type="text/javascript" src="/static/js/jquery.countdown/jquery.countdown.js"></script>
<!-- JQUERY Countdown -->
<script type="text/javascript">
$(document).ready(function () {
var clock = $("#countdown");
console.log(clock);
$("#countdown").countDown("2017/12/01", function (event) {
console.log("CLOCK WORKS");
$(this).text(
event.strftime('%D days %H:%M:%S')
);
});
});
</script>
HTML
{% block content %}
<div id='billboard' class='flexslider billboards'>
<ul class='slides'>
{% for billboard in billboards %}
<li class='slide' style="background-image: url('{{ billboard.image }}');">
<div class='transparent-overlay'></div>
<div class='container'>
<div class='slide-content'>
<h1>{% inplace_edit "billboard.header" %}</h1>
</div>
</div>
</li>
{% endfor %}
</ul>
</div>
<div class="home-sub-container">
<div class="col-xs-8" style="border: 1px solid lime;">
<div id="daily-sales-tracker" style="height: 500px; background-color: lightgray; margin-bottom: 30px;"></div>
<div id="additional-plugins" style="height: 500px; background-color: lightgray;"></div>
</div>
<div class="col-xs-4 red-alerts">
<p>RED ALERTS</p>
<div class="styled-divider">
<div class="color"></div>
<div class="no-color"></div>
</div>
{% for alert in red_alerts %}
<div class="red-alert">
<div class="fa-container">
{% if alert.font_awesome_one %}
<i class="fa {{ alert.font_awesome_one }}"></i>
{% endif %}
{% if alert.font_awesome_two %}
<i class="fa {{ alert.font_awesome_two }}"></i>
{% endif %}
{% if alert.font_awesome_three %}
<i class="fa {{ alert.font_awesome_three }}"></i>
{% endif %}
</div>
<p class="alert-title">
{{ alert.title }}
</p>
<a href="{{ alert.link }}" class="alert-links">
DOWNLOAD
</a>
</div>
{% endfor %}
<div id="countdown">
</div>
</div>
</div>
<div id='sections' class='home-sections'>
{% for section in sections %}
<div class='section-wrapper {% cycle "white" "dark" %}'>
<div class='container'>
<div class='row'>
{% inplace_edit 'section.content|safe' adaptor='tiny' %}
<div class='clear-both'></div>
</div>
</div>
</div>
{% endfor %}
<div class='clear-both'></div>
</div>
{% endblock %}

Include template with dynamic Django form

I have a model with a choices field, and the creation form has different fields depending on the field. I'm implementing the design of a dashboard in which the user can click a button (one button for each choice) and a model containing the model form will be displayed.
I want to use a template only for the model and send the form and action URL to it depending on which button the user clicks, but that would mean I have to mix JS and Django variables and I don't know if that's a good idea.
The code right now is something like this:
dashboard.html
<div class="add-connections">
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.EP %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.OLX %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.CC %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.FR %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
</div>
{% url 'create_olx_connection' as olx_url %}
{% url 'create_ep_connection' as ep_url %}
{% url 'create_cc_connection' as cc_url %}
{% url 'create_fr_connection' as fr_url %}
{% include "properties/dashboard/connection_modal.html" %}
connection_modal.html
<!-- Modal -->
<div class="modal fade modal-property" id="modal-new-connection" tabindex="-1" role="dialog" aria-labelledby="myConnectionModal">
<div class="modal-dialog" role="document">
<div class="modal-content panel-success">
<div class="modal-header panel-heading">
<button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title text-uppercase text-white"><b>Connections</b></h4>
</div>
<div class="modal-body">
<form action="{{ action_url }}"
{{ form.as_p }}
<div>
<button type="submit" class="btn btn-outline-success">Activate connection</button>
Cancel
</div>
</form>
</div>
</div>
</div>
</div>
views.py
def get_context_data(self, **kwargs):
context = super(
ManageServicesView, self).get_context_data(**kwargs)
...
context['connection_forms'] = {
'olx_form': OLXform(),
'el_pais_form': ElPaisForm(),
'finca_raiz_form': FincaRaizForm(),
'calicasa_form': CaliCasaForm()
}
return context
I want something like {% include "properties/dashboard/connection_modal.html" with form=chosen_form and action_url=chosen_url %} but I don't know how to link each button's click event with Django variables to be able to do that. I don't want to code a model for each option, I think it has to be a cleaner way. I'd appreciate your suggestions.
You could put a {% for ... %} loop in connection_modal.html to generate all the modals, with the correct forms, that you need. Than put a another for loop in dashboard.html to create the correct links.
Tweaking views.py:
context['connections'] = {
'OLX': {
'form' : OLXform(),
'user_connected': user_connections.OLX
},
'EP': {
'form' : ElPaisForm(),
'user_connected': user_connections.EP
},
# other connections here
}
dashboard.html:
{% for connection,data in user_connected.items %}
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if data.user_connected %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
{% endfor %}
connection_modal.html:
{% for connection,data in user_connected.items %}
{% if not data.connected %}
<!-- Modal for {{connection}} -->
<div id="modal-new-connection-{{connection}}" class="modal fade modal-property" tabindex="-1" role="dialog" aria-labelledby="myConnectionModal">
<!-- modal code before form -->
{{ data.form }}
<!-- modal code after form -->
</div>
{% endif %}
{% endfor %}
This should create as many modals as you need, each with their own id value, that can be called from the appropriate link. For example modal id "modal-new-connection-OLX" will be created with the OLX form and be called from the OLX link.

Categories

Resources