How to put objects in column in Django templates - javascript

I'm developing an ecommerce project. It's my first time with Django, so be patient.
I have some objects in a list, whith so many fields.
I want to put this object in column in my template.
I tried with the but in a for loop it doesn't recognize more than one div.
Is there a method to incolumn my object in my template?
Here's my code:
enter image description here

Here there is nothing to do from backend. you need to handle it in frontend.
You can use a table to display the data as shown below
<table>
<thead>
<th>Nome</th>
<th>Codice</th>
<th>produttore</th>
....
</thead>
<tbody>
{% for l in listprodotti %}
<tr>
<td>{{l.nome}}</td>
<td>{{l.codice_prodotto}}</td>
<td>{{l.prodottore}}</td>
....
<tr>
{% ednfor %}
</tbody>
</table>
For adding extra styles check bootstrap
If you dont want to display them in a table, you can enclose the for loop in a div and add the below css.
<div class="card">
{% for l in listprodotti %}
<div>
...
</div>
{% ednfor %}
</div>
#in styles (css) file
.card{
display: flex;
gap:15px;
flex-wrap: wrap;
}

You didn't write what you're using for the front end, but maybe Bootstrap would be a good alternative.

Related

Link to content of last column of html table created from pandas dataframe

I am creating a dynamic html table, it is populated with data from a pandas dataframe in python. The last column contains a large block of text (article abstract) for each row, making the rows very large and the table hard to read/navigate. I am looking to hide the content of the last column behind a toggle button (either popover or link to a popup window would be fine). I'm using bootstrap css and javascript.
Is there a way to apply an if statement only to the last column/cell? How else can I achieve this?
Thank you very much in advance.
main.py looks like this:
from flask import Flask, render_template
from researchdashboard import combined_dictionaries
app = Flask(__name__)
headings = ("""list of headings""")
for x in combined_dictionaries:
data = combined_dictionaries.iloc
#app.route('/')
def index():
return render_template('index.html', headings=headings, data=data)
if name == "__main__"_
app.run(debug=True)
and the table section in the html looks like this:
<table class="""some specifics for the table design""">
<tr>
{% for header in headings %}
<th>{{ header }}</th>
{% endfor %}
</tr>
<tbody>
{% for row in data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Edit: So I ended up using the following solution:
<tr>
{% for header in headings %}
<th>{{ header }}</th>
{% endfor %}
</tr>
{% for row in range(num_rows) %}
<tr>
{% for cell in data[row] %}
<td>{{ cell }}</td>
{% endfor %}
<td><button type="button" class="btn btn-secondary" data-container="body" data-toggle="popover" data-placement="left" data-content="{{ abstract_data[row] }}">Abstract</button></td>
</tr>
{% endfor %}
</table>
Where data contains the dataframe except for the column the contents of which I want to be hidden. abstract_data contains just said column and is thus called upon seperately. num_rows is generated from a len("""input measure that specifies the number of rows in the table""") function.
Thank you very much for any solutions that were suggested.
EDIT:
If you are fine just showing a popup window, you can check out the example I made in this fiddle
However, if you want to show a modal instead, please mind that there are many accessibility nuances that you'll have to face. It would probably be better to use a library to help with handling all those situations.
ORIGINAL:
in your situation I would use javascript to toggle a class on the table, and then hide the last column based on that class.
You can hide the last column of a row using css this way:
td:last-child {
display: none;
}
You can find a complete example of what I suggest in this fiddle

Jquery Insert element in an other on event

First post here and quite new on javascript/jquery/webstuff but even after some research about the thing I'm trying to do, I didn't manage to find something that made this thing work.
So, here is the context :
I'm creating a schedule with HTML and Javascript/Jquery.
I want to be able to inject an automated generated <span> or something directly by clicking on the day (which is a <td>).
At first I used basic stuff like "getElementById()" but if I manage to do the thing with this, I'm going on a lot of repetitive code. And I'm quite sure I can avoid this.
So basically I wanted to do generic code and be able to get the which the user clicked.
Here is what I managed to do by now:
HTML part :
<table>
<tr>
<th class="day-name">Sun</th>
<th class="day-name">Mon</th>
<th class="day-name">Tue</th>
<th class="day-name">Wed</th>
<th class="day-name">Thu</th>
<th class="day-name">Fri</th>
<th class="day-name">Sat</th>
</tr>
{% set counter = namespace(a=0) %}
{% for x in range(0, 5) %}
<tr class="week">
{% for y in range(0, 7) %}
{% set counter.a = counter.a + 1 %}
<!-- <td id="2" class="day" onclick="addEvent()"><span class="number">{{ counter.a }}</span></td> -->
<td id="day_{{ counter.a }}" class="day"><span class="number">{{ counter.a }}</span></td>
{% endfor %}
{% endfor %}
</table>
Javascript Part :
function addEvent(){
var node = document.createElement("span");
node.setAttribute("class", "event");
document.getElementById("2").appendChild(node);
};
$(document).ready(function(){
$("td").click(function(){
alert("Ahahahah");
var node = document.createElement("span");
node.setAttribute("class", "event");
document.getElementById(this).appendChild(node);
});
});
The {% ... %} is from Flask/Jinja stuff, but I'm quite sure that's not the problem.
The script is in an other file, but the file is included. (Sure about it because the script "addEvent" works well).
So I tried many, many things, but still not working. The alert pop-up is not even showing up, so I can't try the script. I guess that the way to inject the new element is wrong, but I didn't saw anything with the way I was looking for.
So here it is, thanks in advance for those who take the time to help me on this
I see
onclick="addingEvent()"
but
function addEvent(){
Mabay this is the problem?
You need to use the reference to this and using this can append with it.
$(document).ready(function(){
$("td").click(function(){
alert("Ahahahah");
var node = document.createElement("span");
node.setAttribute("class", "event");
this.appendChild(node);
});
});

Display Product Variant Metafields

I need to display metafields based on the variants selected on the product page. I want them to change as the variants are clicked. I may need some jquery help but I am not that sure how to apply with liquid. Below is my code, any help is greatly appreciated!
{% for variant in product.variants %}
<div id="tab{{ forloop.index0 }}" class="zr-tabs-panel {% if forloop.first == true %}js-active{% endif %}">
<div class="table-responsive>">
<table class="table table-striped">
<tbody>
{% for field in current_variant.metafields.var_meta %}
<tr>
<td>{{ field | first }}</td>
<td>{{ field | last }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endfor %}
The short answer is that you will need to (a): Expose your meta fields to your site's javascript somehow, then (b): Update your variant-changing code to also update the section based on your meta fields.
In many themes, the variant-changing code is contained in a function named selectCallback (though this isn't the case in all themes - if you have trouble finding this code, you can try reaching out to your theme's developer for theme-specific advice).
Whenever you're using Liquid code to put values into Javascript code, I strongly recommend using the json filter - Liquid's magic filter that ensures your output will always be Javascript-legal. (Quotation marks and line breaks will be properly escaped, empty values will be printed as null, etc)

Django Python - Javascript Dynamic Table sorting rows

I have never done any javascript but I saw that this is what I am looking for to display a dynamic table one of my html template.
I have read that there should be something using JQuery but not much more.
So I am looking exactly for an example of dynamic table able to sort rows following which column is selected, written in javascript, displayed in an HTML template, using:
- as columns: the fields of a MySQL table (see example below).
- as rows: the entries contained in the same table
And all of this has to use Django (I don't know if the javascript file either has to be separated from the HTML template or has to be in the HTML template)
Example MySQL table:
CREATE TABLE PDB(
id_PDB_chain CHAR(5) NOT NULL PRIMARY KEY,
id_PDB CHAR(4) NOT NULL,
chaine VARCHAR(10) NOT NULL,
header VARCHAR(255) NOT NULL,
sequence_Proteine TEXT NOT NULL,
start_seq INT NOT NULL,
taille_Proteine INT NOT NULL,
resolution_PDB FLOAT NOT NULL,
meth_Res VARCHAR(10) NOT NULL,
FOREIGN KEY (meth_Res)
REFERENCES methodes_res(meth_Res)
ON DELETE CASCADE
);
Corresponding class in the "models.py" file:
from __future__ import unicode_literals
from django.db import models
class Pdb(models.Model):
id_pdb_chain = models.CharField(db_column='id_PDB_chain', primary_key=True, max_length=5) # Field name made lowercase.
id_pdb = models.CharField(db_column='id_PDB', max_length=4) # Field name made lowercase.
chaine = models.CharField(max_length=10)
header = models.CharField(max_length=255)
sequence_proteine = models.TextField(db_column='sequence_Proteine') # Field name made lowercase.
start_seq = models.IntegerField()
taille_proteine = models.IntegerField(db_column='taille_Proteine') # Field name made lowercase.
resolution_pdb = models.FloatField(db_column='resolution_PDB') # Field name made lowercase.
meth_res = models.ForeignKey('MethodesRes', models.DO_NOTHING, db_column='meth_Res') # Field name made lowercase.
def __unicode__(self):
return self.id_pdb
class Meta:
managed = False
db_table = 'PDB'
In case you need any other informations just ask in comments and I will edit this post with the informations.
In your views.py create a view under whatever name you'd like. Create a list and set it to whatever data you want from your specific model. now go to your template. With that list populated by your specific data you have chosen from the database, use an If statement to check to see if there is anything residing in that list. If there is data there then you can use a For loop like so:
{% for model_name in list_name %}
model_name.model_data etc # Mark it up with relevant html table code, though divs are more preferred
You can mark up the data as needed to display a table, though divs would be more compliant and nicer than tables. This is just a basic example. On the Else statement if no data exists in the list ahead of time, you can simply output that no data exists. Take a look here https://docs.djangoproject.com/en/1.10/intro/tutorial01/
They walk you through building a polling app, where it is relevant to you is the index.html template they build pulling the question data from the database and displaying an unordered list of the questions on the home page as links to vote on. Simply follow this tutorial and look at how they implement the models.py and views.py along with the template and then change the markup from am unordered list to whatever suits your needs.
I found a solution that worked for me and it was really simple in fact:
first you have to download jquery and jquery.tablesorter. Here is the official website where you can download everything and where everything is explained : http://tablesorter.com/docs/
Then, as I work with Django my HTML templates are in a "myapp/templates" directory and my CSS and Javascript files are in a "myapp/static/myapp/" directory.
Here is the template I used:
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'myapp/style.css' %}" />
<script type="text/javascript" src="{% static 'myapp/jquery-3.2.0.min.js' %}">
</script>
<script type="text/javascript" src="{% static 'myapp/jquery.tablesorter.min.js' %}">
</script>
<script type="text/javascript">
$(document).ready(function()
{
$("#pdbtable").tablesorter();
}
);
</script>
</head>
{% if protdb %}
<table id="pdbtable" align="center" border="3" width="100%">
<thead>
<tr>
<th>PDB Id</th>
<th>Chain</th>
<th>Header</th>
<th>Size</th>
<th>Resol.</th>
<th>Method Res.</th>
</tr>
</thead>
<tbody>
{% for i in protdb %}
<tr>
<td>{{ i.id_pdb }}</td>
<td>{{ i.chaine }}</td>
<td>{{ i.header }}</td>
<td>{{ i.taille_proteine }}</td>
<td>{{ i.resolution_pdb }}</td>
<td>{{ i.meth_res }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No PDBs are available.</p>
{% endif %}
And here is my corresponding view:
def pdbinfo(request):
protdb = Pdb.objects.order_by('id_pdb_chain')\
[:len(Pdb.objects.order_by('id_pdb_chain'))]
context = {
'protdb': protdb
}
return render(request, 'pdbapp/pdbinfo.html', context)
As you maybe know, since you are using Django, your template has to receive all informations from a view in views.py and the table of your database (in my case I use MySQL) have to be filled with entries.
This code is working, take some inspiration from it.
One other content that helped me and that gives more details is a youtube video, check the link here: https://www.youtube.com/watch?v=-wAWfPVXlME&t=334s
I hope it will help!

Combining ng repeat and django template language

I have a table that will have varying columns over time and I want my django view to support those changing columns. I also want to use ng-repeat to do some fancy stuff with it such as filtering and other things. However I am having trouble combining the two.
I am passing in the arbitrary col_names with django template language. packages is also sent in with the django template language and is essentially a json array where each row is a dict mapping col_name to some value. i.e.
$scope.packages = [{'col1': 'row1col1', 'col2': 'row2val2'}, {'col1': 'row2col1' ....
However when I go to put in the rows using packages I can't "nest" my templates. Is there a way to grab arbitrary values out of each row in `packages?
<input ng-model="search" placeholder="Search">
<table style="width:100%;">
<thead>
<tr>
<th>Permanent Column 1</th>
<th>Permanent Column 2</th>
{# changing columns #}
{% for col_name in col_names %}
<th>{{ col_name }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr ng-repeat="package in packages | filter:searchPackage">
{% for col_name in columns %}
<td>{{package.{{ col_name }}}}</td> DOESN'T WORK!
{% endfor %}
</tr>
</tbody>
</table>
In that problem line I essentially want to have {{package.ACTUAL_ARBITRARY_COL_NAME}} but I don't know how to do that programmatically
The problem
By default, Django and AngularJS use the same tokens {{ and }} for templating.
So this gets first processed by Django template
{% for col_name in columns %}
<td>{{package.{{ col_name }}}}</td> DOESN'T WORK!
^ ^
|________________________|
Django template will try to process this value
Because Django tries to expand what's inside the first {{...}}, you will not get what you want AngularJS to see.
If you want to continue down that road, I suggest you read some solutions to this problem here
Better solution
A better approach is to give AngularJS the items you want Django to loop for you.
$scope.columns = [...];
Then use AngularJS to do all the loops. Whichever way you do it, if you need it done in AngularJS, better do it all in AngularJS and not half-Django half-AngularJS.

Categories