changing class of element in django template using javascript function - javascript

In my django template I have some Event items listed using a for loop.The event has an associated date_of_occurrence attribute which is a python DateTime.I need to make the background for the event red ,if the datetime is less than current datetime.
I thought of doing it like this
In template
<ul>
{% for event in events %}
<div id="event_div"
<li>
event.name<br>
event.date_of_occurrence
</li>
</div>
{% endfor %}
</ul>
In css
.pastevent{
background-color:red;
}
I need a javascript function to set the class of element with id event_div to pastevent.Can someone tell me how this function can be implemented?
As I understand the function is not fired by any click event ,but when page loads. How will the datetime value of event passed from the template to do the comparison to the current javascript date?

You wouldn't necessarily have to use javascript to do this. There are a couple of different options using the template tags.
The simpler approach (and more crude) would be to render the current datetime to the template as eg. current_date then do a logic check in your template.
{% for event in events %}
{% if event.date_of_occurrence < current_date %}
<div id="pastevent">
{% else %}
<div id="event_div">
{% endif %}
<li>
event.name<br>
event.date_of_occurrence
</li>
</div>
{% endfor %}
The other option would be to create a custom template filter that returns whether the event was in the past or not and apply the same logic as above.

Related

How to select the individual id of an HTML element that is within a for loop in a Django template?

I am trying to select an HTML button that is within a for loop in a Django template using a querySelector to add an event listener to it in JavaScript. How do you create a unique id for the button and select it through JavaScript? Right now, I have one id set to the button within the for loop, and when you press the button, nothing happens.
html
% for post in page_obj.object_list %}
<div class = "individual_posts">
<h5 class = "post_user">{{ post.user }}</h5>
<h6 id = "post_itself">{{ post.post }}</h6>
{% if post.user == request.user %}
<button id="editButton" class="edit_button">Edit</button>
{% endif %}
</div>
{% endfor %}
JavaScript
document.addEventListener('DOMContentLoaded', function(){
document.querySelector('#editButton').onclick = edit_email();
})
All of your buttons will have the same HTML id, one easy way of differentiating would be to include the forloop counter like so:
id="editButton{{ forloop.counter0 }}"
Then you can specify the button in your javascript.
However, I imagine you want to add the onclick functionality to all buttons. Your JS is selecting based on id using the # selector, if you change it to ('.edit_button') it should work for all buttons

Using a variable to for loop using django

I'm very new to python and django framework. I'm facing a minor issue of not being able to assign a variable to my for loop.
In my html file there are buttons and a list (rendered using a loop).
for ex:
Buttons
<li><a class="layer-item" href="#" onclick="selectLayer('base')" title="Base layer">Base layer</a></li>
<li><a class="layer-item" href="#" onclick="selectLayer('soil')" title="Soil layers">Soil layers</a></li>
Inside script tags i'm updating the variable value as
<script>
var layerType = "";
function selectLayer(layer){
layerType = layer;
}
</script>
Also i have a loop like following in the same html file
{% for layer in base %}
<div class="col-4">
<span class="base-layer-title d-block">{{layer.title}}</span>
</div>
{% endfor %}
Here i want to replace base according the button clicked.
For ex:
<a class="layer-item" href="#" onclick="selectLayer('soil')" title="Soil layers">Soil layers</a>
Clicking on the above button should make the for loop as
{% for layer in soil %}
<div class="col-4">
<span class="base-layer-title d-block">{{layer.title}}</span>
</div>
{% endfor %}
From i read you can do something like this to assign a value to a variable.
{% with name="World" %} But not sure how to implement it in my issue.
Any help is appreciated
Also i have a loop like following in the same html file
{% for layer in base %}
{{layer.title}} {% endfor %}
Here i want to replace base according the button clicked.
In short, Django is a server-side framework and it cannot directly respond to any client-side activity. You cannot do it effectively without client-side libraries like React, JQuery, etc.
Workaround 1
You can make a new request to the server on click and re-render the entire page with new parameters.
urls.py
path('my_pattern/<slug:my_layer>', myview)
views.py
def myView(request, my_layer):
# your logics
base = get_layer_data(my_layer) # <-- logic to get list dynamically
return render(request, 'my_template.html', context={'base':base})
my_template.html
{% for layer in base %}
<div class="col-4">
<span class="base-layer-title d-block">{{layer.title}}</span>
</div>
{% endfor %}
...
<a class="layer-item" href="/my_pattern/soil" title="Soil layers">Soil layers</a>
<a class="layer-item" href="/my_pattern/some_other_layer" title="Some other layers">Soil layers</a>
...
The base will have dynamically generated data on every request.
Workaround 2
You can, however, render all the data on the page and control it using collapse in bootstrap https://getbootstrap.com/docs/4.5/components/collapse/

Open the xx.html file based on drop down menu from Navigation bar, code is written in Django-Python

The code is written in Django-Python. The project is created using the models in Django and shown in navigation as dropdown menu.
The drop-down menu is shown using the Django-HTML as shown in following way:
This code works well for dropdown menu. but I want to open the different project url based on click.
I am not sure exactly how to assign id and use javascript to code do onclick bsed html loading !!
I have tried some javascript code, but I am novice.. so If I put here.. it would be more confusing.
<div class="dropdown-menu" id="navbarDropdown">
{% if project_records %}
{% for p in project_records %}
{{ p.pName }}
{% endfor %}
{% endif %}
</div>
I expect that projectB.html will be loaded if click projectB in dropdown menu in navigation bar.
Add the href attribute in anchor tag appropriately. Assuming http://someurl/ is the prefix and the project name is the suffix of your project URLs, you may form the target URL in a variable and use it. Here is your modified code:
<div class="dropdown-menu" id="navbarDropdown">
{% if project_records %}
{% for p in project_records %}
{% with project_url="http://someurl"|add:p.pName %}
{{ p.pName }}
{% endfor %}
{% endif %}
</div>

JavaScript Function Doesn't Work On Django

When the first page is loaded, I want the user to come across all the music, but if he selects a list from RadioButton, I only want the music in that list, but the javascript function doesn't work.
Let me add that I don't normally know JavaScript, but I need to use it.
<div style = "margin-top : 100px;"class = "container">
{% for table in tables %}
<input type="radio" name="list1" onclick="mL('{{table}}')"> {{table}}
{% endfor %}
<div align="center">
<audio class="my_audio" controls="controls" autoplay="autoplay" style="width:500px;"></audio>
<ul>
{% for table in tables %}
{% for music in musics %}
<li style="list-style-type:None">
<a id="{{table}}" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a>
</li>
{% endfor %}
{% endfor %}
{% for music in musics %}
<li style="list-style-type:None">
<a id="default" href="javascript:void(0);" onclick="playSong('{{music}}')">{{music}}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
<script> function mL(x)
{
{% for table in tables %}
if (x=={{table}})
document.getElementById("{{table}}").style.display="block";
document.getElementById("default").style.display="none";
{% endfor %}
else
document.getElementById("{{table}}").style.display="none";
document.getElementById("default").style.display="block";
return;
}
</script>
This isn't a Django issue, it's purely about the JavaScript (or should be).
Here are some problems with your code:
In HTML, the id attribute should be unique in the document. You seem to have many <a> tags with the same id. Use the class attribute, or even better use your own data attribute like data-table.
You can code generate JavaScript using Django template tags like you have, but I think it's a bad idea because it's very hard to reason about how the code will work. Don't use {% for %} inside the <script> block.
JavaScript doesn't use spaces for code blocks like Python does. You need to use braces { } instead.
Once those things are fixed, use the debugging console in your browser (F12 in Firefox and Chrome). It will let you see any syntax errors, and you can even run code in the console to see how things like document.getElementById work.

Twig - Showing/Hiding Element Based Upon Date

I am looking to customize a Twig template by making the display of an element (i.e. a url link) sensitive to the current date. As I'm fairly new to Twig, would Twig have any in-house ways to facilitate this, or would I most likely utilize some Javascript to achieve this?
Thanks for any leads.
You could use the date-filter and the special keyword NOW to achieve this
{% if "NOW"|date('U') > '2018-06-10'|date('U') %}
Show this
{% endif %}
{% if "NOW"|date('U') > '2029-06-10'|date('U') %}
Don't show this
{% endif %}
do note that you could just pass the date as a DateTime to your template to avoid the static code in the template`

Categories

Resources