How to display querysets in Django? - python

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).

Related

How to modify the view to only show the data to one assigned user?

Problem:
I would like to assign a bank statement for each user. Each user will log in using their username and password, and access their document. At the moment, one user can see the statement of all users.
Option 1:
I`ve added a manytomany relationship for the user to the model. When logged in on the Admin interface, I can assign the Bank Statement to the user.
Question:
What is the right way to define the views.py or the html file to only show the bank statement to the user logged-in.
models.py
class BankStatement(models.Model):
user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='bs')
name = models.CharField(max_length=20)
date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
views.py
#login_required(login_url="/login/")
def bankstatement_detail(request, bankstatement_id):
bankstatement = BankStatement.objects.get(pk=bankstatement_id)
context = {
'bankstatement': bankstatement,
}
return render(request, 'administration/bankstatement_detail.html', context)
#login_required(login_url="/login/")
def index_bankstatement(request):
user = request.user
bankstatement = BankStatement.objects..filter(user=request.user)
context = {
'bankstatement': bankstatement,
}
return render(request, 'administration/bankstatement_detail.html', context)
bankstatement_detail.html
<div class="card-block table-border-style">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Date Created</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody>
{% for bankstatement in bankstatements %}
<tr>
<td>{{ bankstatement.id }}</td>
<td>{{ bankstatement.name }}</td>
<td>{{ bankstatement.date_created }}</td>
<td>{{ bankstatement.last_updated }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
Many Thanks
I do not know if you are still working on this one, but
I do not agree with linking of the BankStatement to the User as ManyToMany. In my opinion, one user can have many statements, but one statement has only one user. So it is a one to many relationship defined by Foreign Key.
Let's fix the view:
#login_required(login_url="/login/")
def bankstatement_detail(request, bankstatement_id):
# this line forces to show the statement of the logged in user
user = request.user
bankstatement = BankStatement.objects.get(pk=bankstatement_id, user=user)
context = {'bankstatement': bankstatement,}
return render(request, 'administration/bankstatement_detail.html', context)

converting and multiply float to int in django templates

I am fetching some data from a stocks API and I get some values (stored in the DB as float)
as follow:
YTD Change 0.379996
daily % change 0.00854
my view is as follow:
def get_stock(request):
empty = True
localStocks = Stock.objects.all()
if len(localStocks) > 0 :
empty = False
return render (request,'get_stock.html',{'empty':empty, 'output':list(localStocks)})
and my template
<section class="section-typography container u-readable">
<table>
<thead>
<tr>
<th>Ticker</th>
<th>Name</th>
<th>Price</th>
<th>Last Time</th>
<th>% Change</th>
<th>52W High</th>
<th>52W Low</th>
<th>YTD Change</th>
</tr>
</thead>
<tbody>
{% if not empty %}
{% for list_item in output %}
<tr>
<td> {{list_item.symbol }}</td>
<td> {{ list_item.companyName }}</td>
<td> {{ list_item.latestPrice }}</td>
<td> {{ list_item.latestTime }}</td>
<td> {{ list_item.changePercent }}</td>
<td> {{ list_item.week52High }}</td>
<td> {{ list_item.week52Low}}</td>
<td> {{ list_item.ytdChange }}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</section>
{% endblock %}
the % change for the stock YTD is not 0.379996 but 37.99% and this is what I would like to display. Similarly the daily change is not 0.00854 but 0.85% . How can I manipulate the date either on the view or template to basically multiply it and display only the first 2 decimals of the float?
You need to implement a custom template tag. In your app directory create a new module named templatetags. Inside this module there should be a blank __init__.py and a random named file like percentage.py.
Your percentage.py should contain:
#percentage.py
from django import template
register = template.Library()
#register.simple_tag(name="percentage")
def percentage(value):
return str(round(value *100,2))+'%'
In any html file you want to use this tag, you should load this tag at the start of the file with {% load percentage %}. In order to pass the required value to the templatetag, you need to use it like: {% percentage list_item.changePercent %}
The best way is to change the value in view as follow:
YTD_to_pass = ((YTD*10000)//1/100)
this will multiply the value by 100 and keep 2 digits after whole number
then simply add a % symbol in template.

Django - how to make a link in an html template open an app and pass a objects value as a parameter

Hello I have an app that displays some database information in a table. Inside of the html template I am making an edit link that I want to open another app(page viewLit) while passing a value to it's view. I have added my code below. My question is I am unsure of how to make this links url and pass the object data located inside circuit.circuitid along with it. I haven't been able to find the right way to code this yet and this is just how I thought that this should be done. If anyone has a better idea I am open to suggestions.
search_custom.html(code for link)
{% for circuit in filter.qs %}
<tr>
<td class="actions">
View
</td>
<td>{{ circuit.circuitid }}</td>
</tr>
{% endfor %}
myapp/myapp/urls.py
urlpatterns = [
path('viewLit/', include('viewLit.urls')),
]
myapp/viewLit/urls.py
urlpatterns=[
path('viewLit/circuitid.id', views.viewLit, name='viewLit'),
]
myapp/viewLit/views.py
def viewLit(request, circuitid):
#display records fields here
return HttpResponse("You are at the viewLit page!")
Have a look at the documentation:
Django documentation
myapp/viewLit/urls.py
urlpatterns=[
path('viewLit/(?P<circuit_id>\w+)', views.viewLit, name='viewLit'),
]
html- template:
search_custom.html(code for link)
{% for circuit in filter.qs %}
<tr>
<td class="actions">
View
</td>
<td>{{ circuit.circuitid }}</td>
</tr>
{% endfor %}

Django: Accessing list attributes in template

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.

Django form field issue with model formset

I'm having an issue with rendering individual form fields in a template. I have a model formset that I'm re-ordering after creation to make displaying a little easier on the template. Nothing too complicated, but rendering the form fields isn't working. You can see in the template where I try and render {{ form.train }}, but nothing shows up in the output. However, the form is definitely there because {{ form.instance.user.name }} works correctly.
I opened up PDB and inspected the form variable that I'm adding into the dictionary, and it says <django.forms.widgets.ScheduleForm object at 0x10c58bc50>. I'm not sure if that helps or not, but I wanted to provide as much info as possible.
The Model Form
class ScheduleForm(ModelForm):
class Meta:
model = models.Schedule
fields = [
'train',
'semi',
'tri_axle',
'flow_boy',
'misc',
'material',
'notes'
]
views.py
formset_fields = ('train','semi','tri_axle','flow_boy','misc','material','notes')
ScheduleFormSet = modelformset_factory(models.Schedule, fields=formset_fields, extra=0)
formset = ScheduleFormSet(queryset=queryset)
# Getting form in the right format
ordered_forms = {}
for form in formset:
# Make sure the job exists on the object
if not form.instance.job.number in ordered_forms:
ordered_forms[form.instance.job.number] = {}
# Make sure the user exists on the object
if not form.instance.user.name in ordered_forms[form.instance.job.number]:
ordered_forms[form.instance.job.number][form.instance.user.name] = []
# Append to correct place.
ordered_forms[form.instance.job.number][form.instance.user.name].append(form)
# Dict will look like
# { 'jobID' : { 'user' : [form1,form2,form3] } }
Template
{% for job, users in ordered_forms.items %}
<h2>{{ job }}</h2>
{% for user, forms in users %}
<table class='table striped'>
<thead>
<tr>
<th>{{ user }}</th>
<th>Train</th>
<th>Semi</th>
<th>Tri-Axle</th>
<th>Flow Boy</th>
<th>Misc</th>
<th>Material</th>
<th>Notes</th>
<th></th>
</tr>
</thead>
<tbody>
{% for form in forms %}
<tr>
<td>{{ form.instance.broker.name }}</td>
<td>{{ form.train }}</td>
<td>Semi</td>
<td>Tri-Axle</td>
<td>Flow Boy</td>
<td>Misc</td>
<td>Material</td>
<td>Notes</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
{% endfor %}
Turns out I forgot to add .items to {% for user, forms in users %}.
{% for job, users in ordered_forms.items %}
<h2>{{ job }}</h2>
{% for user, forms in users.items %}
<table class='table striped'>
....
{% endfor %}
{% endfor %}

Categories

Resources