Django: Accessing list attributes in template - python

I have a SQL query in a Django view and store the results in a variable. As far I know the result should be stored as a list.
def assignments(request):
cursor = connection.cursor()
cursor.execute("SELECT o.article_id, o.amount, m.id, o.create_date, m.status FROM orders o, producers p, machines ma, matches m WHERE ma.producer_id=1 AND m.machine_id = ma.id AND m.order_id = o.id")
articles = cursor.fetchall()
context = {"article_list": articles}
return render(request, 'assignments.html', context)
Then I want to transfer that data row by row in a table in my template.
{% block body %}
<div class="container">
<table class="table">
<thead>...</thead>
<tbody>
{% for articles in article_list %}
<tr>
<td>{{ articles.article_id }}</td>
<td>{{ articles.amount }}</td>
<td>{{ articles.id}}</td>
<td>{{ articles.create_date }}</td>
<td>{{ articles.status }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Unfortunately the table is empty and is not showing any results.
The query itself should be fine. I tested the query in my database workbench and it is showing the correct results.
How can I access the data stored in variable articles from my template?
PS: I'm far from being a programmer. So I don't really know any programming concepts/language.
Any help is highly appreciated. Thanks!

You have a list of lists. Each element in articles_list is just a list of values from the database; it does not have any knowledge of attributes like "id" or "amount".
As Arpit says in the comments, you should be using Django models for this rather than raw SQL.

Related

passing variable to a table in flask

I am following this video and everything is working perfectly. The output of a SQL query is saved within a variable that I can call on in another .html page.
so my sql query is:
#app.route('/all_data')
def all_data():
customers = db.get_customers()
for customer in customers:
var = customers
return render_template('all_data.html',var=var)
When calling this {{var}} in all_data.html page the output is for a long tuple:
('name','email','comment','gender'),('name','email','comment','gender') etc etc
I am looking to put this {{var}} into a table instead?.. I but am hitting a brick wall in finding out how to do this?
any help would be much appreciated!
Assuming you're using Flask's default template engine (Jinja2), you can simple use a for loop to iterate over the elements of the collection inside the template. The syntax is:
{% for item in items %}
{{ item }}
{% endfor %}
So simply create an HTML table, and add a row for each item in your var variable.
IIRC, Jinja tuples act the same as Python's, so you can probably do something along the lines of:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Comment</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{% for current in var %}
<tr>
<td>{{ current[0] }}</td>
<td>{{ current[1] }}</td>
<td>{{ current[2] }}</td>
<td>{{ current[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I haven't checked it (as I don't have a Flask project available right now), but if my memory serves me right, that's how I would do it
Here's a link to an usefull part of Jinja2's documentation
Also, what is this piece of code for ?
for customer in customers:
var = customers
You're iterating over each element of the list, but your never use the customer variable (containing the current element). Instead, you assign the var variable to the customers list multiple times. Assuming customers is a simple Python list, you could remove this loop and simply do return render_template('all_data.html',var=customers)

HTML FLASK using {% for %} in JSON data

I am using google firebase which returns data in JSON, compared to SQLAlchemy which returns it in something else.
In SQLAlchemy, I can fetch a database, pass it as a variable in flask render_template, and do something like this to display all the tables.
{% for Order in query %}
<tr>
<td>{{ Order.uuid }}</td>
<td>{{ Order.costusd }}</td>
<td>{{ Order.costcry }}</td>
<td>{{ Order.orderinfo }}</td>
<td>{{ Order.userpaid }}</td>
</tr>
{% endfor %}
If I attempt this with firebase/JSON data, it will display empty tables (the amount of tables that I have data in firebase) but with no data. I tried to do order['uuid']. etc for all of them, but that does not work either.
So, I am trying to display my database in the same way that SQLAlchemy can do it, but i am using a NOSQL database that is JSON.
This was a duplicate
Working code to translate the NoSQL data into jinja2 readable:
r = json.dumps(json_onject)
loaded_r = json.loads(r)
return render_template("report.html", items=loaded_r)

How to display querysets in Django?

I write a functiın and the final, function creates several model objects (same model different values). I listed these objects but I want to list just one time with the same dashboard_id value.
I found something about that but I have an issue with displaying in the table.
It is working but does not display the values. How can I solve it?
views.py
def reports_list(request):
report_list = Reports.objects.values_list('dashboard_id', flat=True).distinct()
context = {
'report_list': report_list,
}
return render(request, "report_list.html", context)
report_list.html
<table id="table_id" class="display">
<thead>
<tr>
<th>Kullanıcı</th>
<th>Yüklenme Tarihi</th>
<th>Görüntüle</th>
</tr>
</thead>
<tbody>
{% for report in report_list %}
<tr>
<td>{{ report.user.first_name }} {{ report.user.last_name }}</td>
<td>{{ report.created_at }}</td>
<td>view</td>
</tr>
{% endfor %}
</tbody>
</table>
to be clear:
I do not think what you have in your function corresponds with what I see as your intention in the template. Therefore you can try this instead:
def reports_list(request, dashboard_id):
report_list = Reports.objects.filter(dashboard_id=dashboard_id).all()
context = {
'report_list': report_list,
}
return render(request, "report_list.html", context=context)
If you think your original function is correct, then you have forgotten to add the context (context=context).

Django - Too slow database record read

I have a database with about 1500 records about one class. I'm also using jQuery Datatables to list the records.
views.py:
records = Animal.objects.all()
return render(request, 'animals.html', {'records': records})
template:
{% for record in records%}
<tr>
<td>{{ record.id }}</td>
<td>{{ record.specie }}</td>
<td>{{ record.category}}</td>
<td>{{ record.quantity }}</td>
</tr>
{% endfor %}
But, it is very very slow. Even reducing the number of records to 100 it takes about 20~45 seconds to fully load a page. Doing the same select to find all 1500 records directly on database takes only 1 second.
As I am using jQuery DataTables to paginate and search the values, is there a way to improve this loading table time?
EDIT:
I used the django debug toolbar and I got these results:

Python/Django: How to show both main model and 'foreign-key model' together in HTML

Good Day SO, I am a beginner in Django and python, just started learning two days ago. Currently, I am trying to do my filtering of data in views.py and creating a context to be shown in my main page that contains both the initial model and the 'foreign-key' model. However, I am having trouble finding help online, even though this is a simple question.. Here goes..
Models involved:
class Plan(models.Model):
plan_ID = models.CharField(
primary_key=True,
max_length=8,
validators=[RegexValidator(regex='^\w{8}$', message='Length has to be 8', code='nomatch')]
)
plan_crisisID = models.ForeignKey(Crisis, on_delete=models.CASCADE)
plan_status = models.CharField(max_length=50)
class Crisis(models.Model):
crisis_ID = models.CharField(
primary_key=True,
max_length=4,
validators=[RegexValidator(regex='^\w{4}$', message='Length has to be 4', code='nomatch')]
)
crisis_name = models.CharField(max_length=50)
Views.py for HTML:
def home(request):
template = loader.get_template('pmoapp/home.html')
crisisList = Crisis.objects.filter(crisis_status='Ongoing').order_by('-crisis_ID')
context = {
'crisisList': crisisList,
#'planList': planList
}
return HttpResponse(template.render(context, request))
And finally, my HTML page:
<tbody>
{% if crisisList %}
{% for crisis in crisisList %}
<tr>
<td>{{ crisis.crisis_ID }}</td>
<td>{{ crisis.crisis_name }}</td>
<td>{{ crisis.crisis_dateTime }}</td>
<td>planid</td>
<td>planstatus</td>
</tr>
{% endfor %}
{% else %}
<p>No crisis available.</p>
{% endif %}
</tbody>
I have several things that I do not know how to do here.. so sorry and bear with me..
As seen above, I am currently only able to show the attributes of the Crisis model, and I do not know how to show the Plan, nor how to filter the data to get the plan with the same crisis ID and highest plan ID
I have a many-to-one relationship between Crisis and Plan, such that a Crisis can have multiple plans, linked by 'Foreign-key': plan_crisisID. I would like for the HTML to show all Crisis objects, and the plan with the highest id value and belonging to the same crisis in the HTML format seen above (planid, planstatus).
I know that the logic portion of this code is done in views.py, however I do not know how to start, or what to do.. Thank you SO for your kind help, I will provide any additional information required.. I have many other similar models with foreign key and many-to-many links and in similar situations.. I hope to learn from answers here so that I can replicate this in other places in my project..
I think that you are on the right track, but should start from the other end because Crisis is on Plan.
In the views pull planlist instead of crisislist, then you can:
<tbody>
{% if planList %}
{% for plan in planList %}
<tr>
<td>{{ plan.crisisID.crisis_ID }}</td>
<td>{{ crisis.crisis_name }}</td>
<td>{{ plan.crisisID.crisis_dateTime }}</td>
<td>{{ plan.plan_ID }}</td>
<td>{{ plan.planstatus }}</td>
</tr>
{% endfor %}
{% else %}
<p>No crisis available.</p>
{% endif %}
</tbody>
Oh and you should probably swap the query to something like:
planList = Plan.objects.filter(crisis_ID__crisis_status='Ongoing').order_by('-crisisID__crisis_ID')

Categories

Resources