Hi I am looping through items being passed through the context but nothing is showing.
This is the data I have:
{"error":[],"result":{"USDT":"60000.00000000","CHZ":"13773.0349000000","ZRX":"0.0000000000","ZUSD":"67787.8285","DOT":"0.0000000000","COMP":"0.0000034600","ENJ":"257.6815000000","ADA":"2473.80445621","XXDG":"17006.92601155","ALGO":"32063.69514500","XXBT":"0.0000012880","SUSHI":"172.4585500000","SOL":"1133.3543869800","DASH":"0.5104491200","LINK":"144.2407000000","ATOM":"151.26763831","XXLM":"6926.27220000","XXRP":"0.00000000","XETH":"14.5877343640","TRX":"923.80015900","KNC":"0.0000000000","BAL":"0.0000000000","XLTC":"11.4923900000","KSM":"24.7142610000","SC":"0.0000000200","OCEAN":"652.6077000000","MATIC":"1838.9295772000","AAVE":"83.6218990800","ZGBP":"30622.0790","XZEC":"0.0000073100"}}
It is passed in my context like this:
def kraken(request):
""" A view to return kraken page """
context = {
'api_reply': api_reply,
}
return render(request, 'home/kraken.html', context)
And inside my template I have this:
{% for k, v in api_reply.items %}
<tr>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
I have no errors showing but it is not displaying, any help would be great thank you.
The items are stored in the result subelement, you thus should enumerate over api_reply.result.items, not api_reply.items:
{% for k, v in api_reply.result.items %}
<tr>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
Furthermore you need to convert the JSON blob into Python objects, for example with:
import json
def kraken(request):
""" A view to return kraken page """
context = {
'api_reply': json.loads(api_reply),
}
return render(request, 'home/kraken.html', context)
Related
I have queries like following that I would like to implement it in front end:
MembershipPayment.objects.filter(group__name=tg.group_name).are_valid().count()
MembershipPayment.objects.filter(group__name=tg.group_name).Not_valid().count()
I know that I can pass this from view to front-end HTML, but the problem is that in the front end I have a query-set containing many "group"s. so I need to run a similar query for each of those "group"s.
I need something along these lines [this code of course won't work] in front:
{% for rec in groups %}
<tr>
<td>{{ MembershipPayment.objects.filter(group__name=tg.group_name).are_valid.count }}</td>
<td>{{ MembershipPayment.objects.filter(group__name=tg.group_name).not_valid.count }}</td>
</tr>
{% endfor %}
So I was wondering how can I achieve this without changing my model structure (if possible).
Why don't you do that logic in your view, by building a dict for each of your group, like:
def your_view(request):
...
groups: dict = dict()
for group_name in group_names:
groups[group_name]: int = MembershipPayment.objects.filter(group__name=group_name).are_valid().count()
return render(request,'your_template.html', {'groups': groups})
..and then pass it to your template, like:
{% for key, value in groups.items %}
<tr>
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
{% endfor %}
...key being the group name, value being the group count.
I ended up passing a dictionary like this in view:
groups_statistics={group1:{monthly_balance:250,weekly_balance:3000},group2:{monthly_balance:250,weekly_balance:3000}}
and then looping through its value as:
{% for rec,stat_dic in groups_statistics.items %}
<tr>
<td>{{ stat_dic.weekly_balance| get_value_from_dict:rec }}</td>
<td>{{ stat_dic.monthly_balance| get_value_from_dict:rec }}</td>
</tr>
{% endfor %}
here get_value_from_dict is a customized tag defined in dictionarytags.py as:
from django import template
register = template.Library()
#register.filter('get_value_from_dict')
def get_value_from_dict(dict_data, key):
"""
usage example {{ your_dict|get_value_from_dict:your_key }}
"""
if key:
return dict_data.get(key)
in the following folder:
my app>"templatetag" folder.
this folder contains:
__ init __.py
and
dictionarytags.py
and then in html I have this line in upper part:
{% load dictionarytags %}
There is a module with 30 columns.
I query this table in the views.py to get the last record (last row).
To get the data in template (index.html), I have to write each column and in front of it, its value. I have to do it 30 times!
is there anything like {{form}} to get all the columns and their value automatically or at least by using {% for ... %}?
in views.py
def articlesindex(request):
data = Articles.objects.all().last()
return render(request, 'Articles\index.html', {'articles':data})
in index.html
{{ articles }} (does not work)
{{ articles.a_table }} (does not work)
{% for k,v in articles %} (does not work)
<tr>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
That is because last() return a single object in a queryset (see the documentation here). So, as it is a single object you will have a single row. You can render the object as follow:
<tr>
<td>{{ articles.attr_1 }}</td>
<td>{{ articles.attr_2 }}</td>
...
<td>{{ articles.attr_n }}</td>
</tr>
The attribute one by one
i am working on my django-admin, and i am trying to render to pdf my obj. This is my def:
def Imprimir(self, request, obj):
data = {
'id':obj.values_list('id', flat=True),
'freguesia': obj.values_list('freguesia',flat=True),
'rua': obj.values_list('rua',flat=True),
'porta': obj.values_list('porta',flat=True),
'tavaria':obj.values_list('tipo_avaria',flat=True),
}
pdf = render_to_pdf('daa/imprimir/avarias_pdf.html', data)
return HttpResponse(pdf, content_type='application/pdf')
https://i.stack.imgur.com/22V1I.png
The problem is only show my queryset and the ID, i want to show the name of the queryset not the id. anyone can help me?
My avarias_pdf.html
<table style="width:100%">
<tr>
<th>ID:</th>
<th>Freguesia:</th>
<th>Rua:</th>
<th>Porta:</th>
<th>Tipo avaria:</th>
</tr>
<tr>
<td>{{id}}</td>
<td>{{freguesia}}</td>
<td>{{rua}}</td>
<td>{{porta}} </td>
<td>{{tavaria}}</td>
</tr>
</table>
This isn't the right way to do this at all. You should remove all those values_list calls, and iterate through the queryset in the template.
def Imprimir(self, request, obj):
data = {'obj': obj}
pdf = render_to_pdf('daa/imprimir/avarias_pdf.html', data)
return HttpResponse(pdf, content_type='application/pdf')
...
{% for item in obj %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.freguesia }}</td>
<td>{{ item.rua }}</td>
<td>{{ item.porta }} </td>
<td>{{ item.tavaria }}</td>
</tr>
{% endfor %}
I need to display a table from my database using only certain columns. In my view I have this:
def home_page(request):
query_results = Model.objects.filter(open=True)
return render(request, 'home.html')
and my home.html page looks like this:
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.col1 }}</td>
<td>{{ item.col2 }}</td>
<tr>
{% endfor %}
</table>
However, when I go to the page, there isn't any data in the table. Am I going about this wrong?
Thanks for your help.
You forget to include query_results to the template context. Try this:
return render(request, 'home.html', {'query_results': query_results})
I am rendering a view to an html template. I do not get any errors but the data does does not loop on the page.
I had this working but once i started using the template I have had problems. So I know it works I am just not understanding using context to render the response.
I am making a request to an api then assigning the response to a variable. Then I am creating the context based on the variable of the response. At this point I understand I should be able to access the data with the context variable. What is the proper way of assigning a response to a a context and using the data in a template tag.
In the view
def github(request):
jsonList = []
req = requests.get('https://api.github.com/users/DrkSephy')
str_response = req.content.decode('utf-8')
jsonList.append(json.loads(str_response))
parsedData = []
userData = {}
for data in jsonList:
userData['name'] = data['name']
userData['blog'] = data['blog']
userData['email'] = data['email']
userData['public_gists'] = data['public_gists']
userData['public_repos'] = data['public_repos']
userData['avatar_url'] = data['avatar_url']
userData['followers'] = data['followers']
userData['following'] = data['following']
moviesList = parsedData.append(userData)
context = {'moviesList': moviesList}
return render(request, 'serviceapp/github.html', context)
In the html file
{% for movie in moviesList %}
<tr>
<td>{{ movie.name }}</td>
<td>{{ movie.blog }}</td>
<td>{{ movie.avatar_url }}</td>
<td>{{ movie.public_repos }}</td>
<td>{{ movie.public_gists }}</td>
<td>{{ movie.email }}</td>
<td>{{ movie.followers }}</td>
<td>{{ movie.following }}</td>
</tr>
{% endfor %}
{% for moviesList in moviesList %}
^both the variables here are identical - you already use moviesList for the whole list, so you cant use it again for the variable inside loop. Use something like this:
{% for item in moviesList %}
{{ item.name }}
...
{% endfor %}
edit:
ok, so I looked at your code again. Have you tried to print the variables in your view if they are filled correctly? Because they are not. Look at this line:
moviesList = parsedData.append(userData)
^ what you do here is you assign the result of parsedData.append() (which is None, because append is in-place modification) to the moviesList variable, which is then None.