Using a Jinja2 for loop with a javascript alert - javascript

I've been trying to create a webpage where after receiving user input, it would display the history of all user input after pressing submit, however this is working as intended. However I wanted to implement an alert box which would show additional information. However as everything else is printed correctly, since the alert box uses an onclick event, it would only output the very last sample of user input.
<!doctype html>
<html>
<head>
<title>Enrolment page</title>
</head>
<body>
{% if all_users %}
{% for user in all_users %}
<h1> Hi, {{ user[0] }}) </h1>
<button onclick="myFunction()">Details</button>
<script>
function myFunction() {
alert("{{ user[1] }}, {{ user[2] }}");
}
</script>
{% endfor %}
{%else%}
No users to show
{% endif %}
</body>
</html>
In my code, all_users is the information from a csv file, however that is working fine. My only problem is the alert is not showing the information I want. Is there a way to store each set of user details in each script to print out each button since it is only displaying the last set of user details.

You can bind the user[0] and user[1] in the myFunction() call like:
{% for user in all_users %}
<h1> Hi, {{ user[0] }}) </h1>
<button onclick="myFunction('{{user[1]}}, {{user[2]}}')">
Detail
</button>
{% endfor %}
Then change the function to:
function myFunction(users) {
alert(users);
}

To work this in Jinja2, you might try using a string variable and appending each value as in (code not tested):
<!doctype html>
<html>
<head>
<title>Enrolment page</title>
</head>
<body>
{% if all_users %}
{% set AllUserList = "" %}
{% for user in all_users %}
{% set AllUserList = AllUserList + user[1] + ", " + user[2] + "\n" %}
<h1> Hi, {{ user[0] }}) </h1>
<button onclick="myFunction()">Details</button>
<script>
function myFunction() {
alert("{{ AllUserList }}");
}
</script>
{% endfor %}
{%else%}
No users to show
{% endif %}
</body>
</html>

Related

Link element tags are disabled when a background image is set

I've got this base.html from which other html documents extend
base.html
<!DOCTYPE html>
<html>
<head>
<--!some css links and jquery source headers-->
<style>
{% block style %}
.container{
position: relative;
}
{% endblock style %}
</style>
</head>
<body>
<div class="container">
{% block breadcrumb %}{% endblock breadcrumb %}
{% block content %}{% endblock content %}
</div>
</body>
<script type="text/JavaScript">
{% block script %}
var imgName = "{% url 'img_file.png' %}";
document.body.style.backgroundImage = "url('"+ imgName.src +"')";
{% endblock script %}
</script>
<\html>
a document that extends from base.html
index.html
{% extends 'base.html' %}
{% block breadcrumb %}
<div class="nav nav-bar nav-bar-dark>
some link
</div>
{% endblock %}
{% block content %}
<form action="view-url" method="post">
{{ form }}
<input type="submit" class="btn" value"Submit">
</form>
{% endblock %}
the submit input works well but the link (to some url) seems to be disabled. When I remove the background image from the base.html, the link works just fine. Any help on what I'm missing here please ,

get list of items, which were passed from python file (Django) to html, from html to Javascript, which is on the same page

my python code:
def index(request):
body=list(Body.objects.all())
loads=list(Load.objects.all().order_by('length'))
badLoads=[]
goodLoads=[]
for load in loads:
if load.length>body[0].length or load.width>body[0].width or load.mass>body[0].mass:
badLoads.append(load)
else:
goodLoads.append(load)
goodLoadsLength=len(goodLoads)
context={
'body':body[0],
'loads':loads,
'badLoads':badLoads,
'goodLoads':goodLoads,
'goodLoadsLength':goodLoadsLength,
}
return render(request,'index.html',context)
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
{% if body %}
<p>body length: {{ body.length }}, body width: {{ body.width }}, body height: {{ body.height }}, body max mass, which can be taken: {{ body.mass }}</p>
{% else %}
<p>No parameters found</p>
{% endif %}
</div>
<div>
{% if loads %}
<ul>
{% for load in loads %}
<li>load id: {{ load.id }}, load length:{{ load.length }}, load width: {{load.width}}, load height: {{load.height}}, load mass: {{load.mass}}</li>
{% endfor %}
</ul>
{% else %}
<p>No loads are available.</p>
{% endif %}
</div>
<div>
{% if goodLoads %}
<ul>
{% for goodLoad in goodLoads %}
<li>load id: {{ goodLoad.id }}, load length:{{ goodLoad.length }}, load width: {{goodLoad.width}}, load height: {{goodLoad.height}}, load mass: {{goodLoad.mass}}</li>
{% endfor %}
</ul>
{% else %}
<p>No loads are available.</p>
{% endif %}
</div>
<div>
{% if loads %}
<ul>
{% for badLoad in badLoads %}
<li>load id: {{ badLoad.id }}, load length:{{ badLoad.length }}, load width: {{badLoad.width}}, load height: {{badLoad.height}}, load mass: {{badLoad.mass}}</li>
{% endfor %}
</ul>
{% else %}
<p>No loads are available.</p>
{% endif %}
</div>
<script>
const loadsLength="{{goodLoadsLength}}";
const goodLoads="{{goodLoads}}"
</script>
</body>
</html>
I would like to do a simple table with the help of javascript on the same page. I know I can do a table through html, but I would like to do it through Javascript, on the same page. But somehow I can see in script simple variables, like this one:
const loadsLength="{{goodLoadsLength}}";
But I cannot do list of items. The number of items can be different. So it should be going through for or forEach loop, but script does not give me any chance to get the members of a list in case of python(or array in case of javascript) into javascript block. If I try:
const goodLoads="{{goodLoads}}";
console.log(goodLoads);
It gives me:
[<Load: Load object (1)>]
Which seems like it sees the object in array. But when I try:
console.log(goodLoads[0].length);
or
foodLoads.forEach(item=>{
console.log(item.length)
})
It gives me: the object is undefined. I tried couple of more approaches like with for loop with for object in objects, or normal for loops with the step++ way. But the object is undefined.
I guess I don't understand how to get the list/array from html to script block. It should be seen as normal array of items. But I cannot get them. Can somebody pinpoint me to the answer? Thank you.
Use the Django built-in json_script (see documentation here) template tag to safely output a python object as JSON wrapped in a script tag. Then in your main JS script, you can parse the JSON object and do all standard operations with it.
In your template:
{{ goodLoads|json_script:"goodLoads"}}
In your main JS file:
let goodLoads = JSON.parse(document.getElementById('goodLoads').textContent);
Another issue is that you're passing QuerySet objects into the context variable goodLoads. It won't be very useful to have those objects in your JS file, because you cannot access the object field values. For that turn the QuerySet object into a dict before passing it to the context.
For example using queryset.values(),
def index(request):
body=list(Body.objects.all())
loads=list(Load.objects.all().order_by('length'))
badLoads=[]
goodLoads=[]
for load in loads:
if load.length>body[0].length or load.width>body[0].width or load.mass>body[0].mass:
badLoads.append(load.values()) #converting to dict here
else:
goodLoads.append(load.values()) #converting to dict here
goodLoadsLength=len(goodLoads)
context={
'body':body[0],
'loads':loads,
'badLoads':badLoads,
'goodLoads':goodLoads,
'goodLoadsLength':goodLoadsLength,
}
return render(request,'index.html',context)

Use twig variables into ajax function

i have a personal mvc architecture and i want to use variables passed from the controller to the twig template into an included js file.
There are my files, All about the variable $server_ID :
DashboardController.php who send the $server_ID variable to the template
class DashboardController extends Controller {
public function get($id = null) {
$serverModel = $this->model('ServerModel');
$server_ID = $serverModel->findById($id);
$this->view('dashboard/get', ['server_ID' => $server_ID]);
}
public function ajax_getstats($server_ID) {
$return = ServerModel::getStats($server_ID);
echo json_encode($return);
exit;
}
}
Twig template main.html that make the layout
<!DOCTYPE html>
<html>
<head>
{% include 'head.html' %}
</head>
<body>
{% include 'header.html' %}
<div class="content">
{% block content %}{% endblock %}
</div>
{% include 'scripts.html' %}
</body>
</html>
scripts.html that include specific js files
<!-- Optional JavaScript -->
<script src="{{ ASSET_ROOT }}/assets/vendor/jquery/jquery-3.3.1.min.js"></script>
<script src="{{ ASSET_ROOT }}/assets/vendor/bootstrap/js/bootstrap.bundle.js"></script>
<script src="{{ ASSET_ROOT }}/assets/js/dashboard.js"></script>
And finaly dashboard.js where what i want to use the variable $server_ID
function getStats() {
var rStart = Date.now();
$.getJSON("http://localhost/site/public/dashboard/ajax_getstats/" + {{ server_ID }}, function(data)
{
// treatment here
});
}
$(document).ready(function()
{
getStats();
});
You can create a hidden input type in the main.html page which contains the value of server_ID, and then grab it in the JavaScript file.
main.html:
<!DOCTYPE html>
<html>
<head>
{% include 'head.html' %}
</head>
<body>
<input type="hidden" id="server-id" value="{{ server_ID }}"> <!-- This echos the server_ID variable to become the value for this input. -->
{% include 'header.html' %}
<div class="content">
{% block content %}{% endblock %}
</div>
{% include 'scripts.html' %}
</body>
</html>
dashboard.js:
let serverID = $("#server-id").val(); // This variable is now equal to $server_ID.
function getStats() {
var rStart = Date.now();
$.getJSON("http://localhost/site/public/dashboard/ajax_getstats/" + {{ server_ID }}, function(data)
{
// treatment here
});
}
$(document).ready(function()
{
getStats();
});

how to load html content in txt file for email confimation, have any suggestion how to do it?

how to load html content in txt file for email confimation
here is my verify.txt file
{% load i18n %}{% blocktrans %}Hello {{user}}!
Please click the link below to verify your email address.{% endblocktrans %}
{{ verification_url }}
if clicking the linkabove doesn't work, please copy and paste the URL in a new browser instead.
Regards,
The Deebaco Development Team
i want to modify this txt file to html file like below,
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap"></script>
</body>
</html>
i just implemented {% block html_body %} then it's work perfect.
{% block html_body %}
{% blocktrans %}You're receiving this email because you need to
finish activation process on {{ site_name }}.{% endblocktrans %}
{% trans "Please go to the following page to activate account:"
%} {{
protocol }}://{{ domain }}/{{ url|safe }}
{% trans "Thanks for using our site!" %}
{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
{% endblock html_body %}

django-dynamic-formset add another / delete buttons failing

[Screenshot of the error]
You can find the screenshot here: https://i.stack.imgur.com/2D4l2.png
Hi,
I'm a beginner Django developer writing my first question in stackoverflow. I'm trying to use the django-dynamic-formset plugin to enable the user of my web application to add or delete forms dynamically, by clicking a button, however, instead of getting a "remove" button for every row, I'm getting one for every field in my form as you can see in the picture. Also, when I'm trying to customize the text in the "add another" or "delete" button, this is not working (you can see the script at the end of my html template). I would appreciate if you can tell me what I might be doing wrong. I'm attaching the code of my html template as well.
`{% load crispy_forms_tags %}
{% load staticfiles %}
<table class="formset-test">
{{formset.management_form|crispy}}
{% for form in formset.forms %}
<tr class="{% cycle 'row1' 'row2' %} formset_row-{{formset.prefix}}">
{% for field in form.visible_fields %}
<td>
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{hidden}}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field|as_crispy_field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<!-- <p class='btn btn-warning' id='agregar'>Agregar Posición</p> -->
<br>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'dynamic_formsets/jquery.formset.js' %}"></script>
<!-- <script type="text/javascript">
$('#agregar').on('click',function(){
$('.formset-test').append()
});
</script> -->
<script type="text/javascript">
$('.formset_row-{{ formset.prefix }}').formset({
addText: 'Agregar posición',
deleteText: 'Borrar posición',
prefix: '{{ formset.prefix }}',
});
</script>
`

Categories