Hide and show elements inside Django HTML template - javascript

I have 2 buttons orders, and suppliers., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".button_order").click(function(){
$(".myorders").show();
$(".mysupplier").hide();
});
$(".button_supplier").click(function(){
$(".myorders").hide();
$(".mysupplier").show();
});
});
</script>
syle.css looks like;
.myorders,
.mysupplier{
font-size: 25px;
display: none;
}
This works perfectly fine until I use normal data like;
<body>
{%block content %}
<button class="button_order" >ORDERS</button>
<button class="button_supplier" >SUPPLIER</button>
<p class="myorders" >
This is my order
</p>
<p class="mysupplier">
my supplier is cool
</p>
</body>
But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part.
<p class="myorders">
{% for element in orders %}
{% for key,val in element.items %}
<ul><li>{{key}}:{{val}}</li></ul>
{% endfor %}
<hr class="new1">
{% endfor %}
</p>
I should get Order data from database only when ORDER button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data.
my views.py looks like
from django.shortcuts import render
client = MongoClient("mongodb://localhost:27017/")
db=client.inventory_data
def home(request):
collection_data_1 = db['orders']
orders = list(collection_data_1.find())
collection_data_2= db['suppliers']
suppliers = list(collection_data_2.find())
return render(request,'home.html',{'orders': orders,'suppliers':suppliers})

The loop in template is executed when rendering template. You pass all your data from view to template. if you just want to hide it from display add to your js:
<script>
$(document).ready(function(){
$(".mysupplier").hide();
$(".myorders").hide();
$(".button_order").click(function(){
$(".myorders").show();
$(".mysupplier").hide();
});
$(".button_supplier").click(function(){
$(".myorders").hide();
$(".mysupplier").show();
});
});
</script>
but if you would like to dynamicly fetch current data from db by pressing button i recommend use htmx (htmx.org)

Related

Show and hide text of different posts

I have several posts each of them composed of three parts : a title, a username/date and a body. What I want to do is to show the body when I click on either the title or the username/date and hide it if I click on it again. What I've done so far works but not as expected because when I have two or more posts, it only shows the body of the last post even if I click on another post than the last one. So my goal is only to show the hidden text body corresponding to the post I'm clicking on. Here is my code:
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Test page{% endblock %}</h1>
<a class="action" href="{{ url_for('main_page.create') }}">New</a>
{% endblock %}
{% block content %}
{% for post in posts %}
<article class="post">
<header>
<script language="JavaScript">
function showhide(newpost)
{var div = document.getElementById(newpost);
if (div.style.display !== "block")
{div.style.display = "block";}
else {div.style.display = "none";}}
</script>
<div onclick="showhide('newpost')">
<h1>{{ post['title'] }}</h1>
<div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%d-%m-%Y') }}</div>
</div>
</header>
<div id="newpost">
<p class="body">{{ post['body'] }}</p>
</div>
</article>
{% if not loop.last %}
<hr>
{% endif %}
{% endfor %}
{% endblock %}
Of course I looked for a solution as much as I could but I'm kind of stuck plus I'm a complete beginner in HTML/JS/CSS. And one last thing, I'm currently using Python's framework Flask. Thank you by advance.
You need to give each of your posts a unique id for your approach to work.
Change your code to
<div id="{{post_id}}">
<p class="body">{{ post['body'] }}</p
</div>
where post_id is that post's unique id e.g. its id in the database you are using that you pass to the template in your view. Then, change the call to the onclick event handler to
<div onclick="showhide('{{post_id}}')">
If you don't have a unique id you can also use the for loop's index: replace all post_id instances above with loop.index. See Jinja's for loop docs for more information.

Load data from flask into html when pressing a button

I am trying to load a variable into a HTML page when pressing a button. The problem is that I already have a function to load the initial page, and the new data shall be loaded on the same page, without redirecting.
This is the code i have by now:
.py file:
#app.route('/')
def index():
return render_template('index.html')
def get_documents():
documents = {'asd': 'as', 'def':'de'}
return render_template('index.html', documents=json.dumps(documents))
index.html file
<div>
<button onclick="Start()" id="StartButton" >Start</button>
</div>
<div id = "feed" style="display: none;">
</div>
<script>
var d = JSON.parse('{{documents | tojson | safe}}');
document.getElementById('feed').innerHTML = d.asd;
</script>
.js file:
function Start()
{
var feed_div = document.getElementById("feed");
feed_div.style.display = "block";
}
I would like that when i press the Start button, the content in the documents structure would appear in the .feed section. How could i do this?
Also, documents will be a list, but here i used a json because i wanted to try some examples i've found.
You can create div element inside the feed element, this element will contain all of your document data and will be hidden
<div id="document" style="display: hidden">
{% for item in documents %}
<div>{{ item }}</div>
{% endfor %}
</div>
and then in javascript change the display of the document element:
function start() {
document.getElementById("document").style.display = "block";
}

Flask jinja2 update div content without refresh page

Need achieve some features like [http://webonise.co.uk/][1] when click on contact,resume,resources link will update (location URL&div content) but without refresh the page.
Flask view function
#app.route('/')
def index():
flash('Welcome')
return render_template('index.html')
Under index.html is extends base.html
{% block content %}
{{super()}}
<section class="content">
<i class="mdi-event"></i>Event
<i class="mdi-contact"></i>Contact
<div class="board">
{# dynamic template #}
{# without using {{% include 'event.html' %}} #}
</div>
</section>
{%- endblock %}
How can i dynamic rendar event.html / contact.html content when different link is click and rendar under {# dynamic template #} without refresh the page ?
<!--event.html-->
<ul class="list">
<li>
<h3>123</h3>
<p>abc</p>
</li>
</ul>
What I try
import jinja2 Environment but still no idea how to achieve this
env = Environment(autoescape=True,
loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
#app.route('/')
def index():
board = env.get_template('event.html')
flash('Welcome Home Tyler')
return render_template('index.html', board=board)
Is there really need ajax technique get/post method to achieve all this?
You can use Flask-Sijax which helps you add Sijax support to your Flask app. Sijax is a python/jquery library that makes AJAX easy to use on your web applications. Alternatively you could do this:
<script>
$(document).ready( function() {
$('#next').click(function() {
$.ajax("{{ url_for('yourroute') }}").done(function (reply) {
$('#container').html(reply);
});
});
});
</script>
<input type="button" id="next" value="Next" />
<div id="container"></div>

How can I reset form after render template and hide modal

I have a django view and I render a template like this:
return render(request, 'submission/submit_url.html',
{'form': form, 'has_modal_info': 1})
On my template (submit_url), I get that variable "has_modal_info" and depending on the value (0 or 1) I decide to call or not my modal:
<!-- Modal content-->
<div class="modal-content">
{% if has_modal_info %}
{% include 'submission/finishing_modal.html' %}
<script>
var finishing_modal = $('#end-submission-modal');
finishing_modal.modal();
</script>
<script>
finishing_modal.on('hidden.bs.modal', function(e){
var id_url_form = $('#id_url_form');
id_url_form[0].reset();
console.log("Your event works!");
});
</script>
{% endif %}
</div>
</div>
</div>
The form I'm trying to reset:
<form id="id_url_form" action="{% url 'pages.submission.views.submit_url' %}" class="form-horizontal" method="post" enctype="multipart/form-data" name="url_form">
After rendering and submitting the form, I call my modal and try to "hook" the hidden event by resetting my form on that event for clearing all fields, but it doesn't work.
Tried Jquery trigger and a lot of possibilities but no success.
My opinion is that this happens because django render is Hooked my my modal call and can't clear the form, but I have no idea how to work this around.
Any suggestions?
Can you try this
id_url_form.each(function(){
$(this).val('')
}

Jquery toggle (visible/invisible) for only the item clicked on in a template-generated html list

Code
<ul>
{% for item in lis %}
<li>
<div id="single-toggle">|Toggle|</div>
<div class="visible-when-folded">
<div class="name">{{ item.name }}</div>
<div class="date">{{ item.date }}</div>
</div>
<div class="invisible-when-folded">
<div class="about">{{ item.about }}</div>
<div class="contact_info">{{ item.contact_info }}</div>
</div>
</li>
{% endfor %}
</ul>
Example output code
|Toggle|
Peter
24-04-1990
A friendly guy
0474657434
|Toggle|
Martha
22-02-1984
An amazing gal
0478695675
|Toggle|
William
12-11-1974
An oldie
0478995675
Desired behavior
I would like that whenever you click on |Toggle| the about(e.g. A friendly guy)
and contact_info(e.g. 0474657434) part dissapear/reappear.
Attempt at solution
$(function(){
$("#single-toggle").click(
function(){ $("div.invisible-when-folded").toggle(); } );
});
But unfortunately this toggles the fields for each item in the list as opposed to only the one I click on.
Edit
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def toggle(request):
lis = [{'name':'Peter', 'date':'24-04-1990', 'about':'A friendly guy',
'contact_info':'0474657434' },
{'name':'Martha', 'date':'22-02-1984', 'about':'An amazing gal',
'contact_info':'0478695675' },
{'name':'William', 'date':'12-11-1974', 'about':'An oldie',
'contact_info':'0478995675' }]
return render_to_response('page.html', {'lis':lis},
context_instance=RequestContext(request))
You need to pass the current object as context in the selector to get the element related to event source object. You also need to use class instead of id or generate unique ids for div with id = single-toggle as html elements are supposed to have unique ids.
Live Demo
I have give the div with id a class="single-toggle"
Change
$("div.invisible-when-folded").toggle();
To
$("div.invisible-when-folded", this).toggle();
You code
$(function(){
$("#single-toggle").click(
function(){ $("div.invisible-when-folded", this).toggle(); } );
});
You need to focus the function on the div within the clicked div... The actual code you need to use is:
$(function(){
$("#single-toggle").click(
function(){ $("div.invisible-when-folded", this).toggle(); } );
});

Categories

Resources