set data in html django - html

I learning django rest. And now i wont output some json data in html. My json:
{'Resul': {'Period Start': '2017-01-01', 'Period End': '2017-12-12'}}
then i send it json to html:
context = {'Resul': json_data['date']}
content = render_to_string('balance.html', context)
json_data['date'] - {'Period Start': '2017-01-01', 'Period End': '2017-12-12'}
in html i write this code
Period: {{ Resul['Period Start'] }} - {{ Resul['Period End'] }}
but have error:
Could not parse the remainder: '['Period Start']' from 'Resul['Period Start']'

I strongly recommend you not to use spaces in dictionary key names, change them for underscores and do it like this:
Period: {{ Resul.Period_Start }} - {{ Resul.Period_End }}

Related

Getting error in printing the dictionary values to html

I want to print to get the details of different cities weather and I had written the code as below. While retrieving the data, I am not able to fetch the data to HTML.
views.py:
from django.shortcuts import render
# Create your views here.
import urllib.request
import json
import requests
def display(request):
city=['vijayawada','guntur','tenali','rajahmundry','amaravathi']
for i in city:
source = urllib.request.urlopen(
'https://api.openweathermap.org/data/2.5/weather?q=' + i + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
list_of_data = json.loads(source)
data = {
"country_code": str(list_of_data['sys']['country']),
"coordinate": str(list_of_data['coord']['lon']) + ', '
+ str(list_of_data['coord']['lat']),
"temp": str(list_of_data['main']['temp']) + ' °C',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
'main': str(list_of_data['weather'][0]['main']),
'description': str(list_of_data['weather'][0]['description']),
'icon': list_of_data['weather'][0]['icon'],
}
print(data)
return render(request, "display.html",data)
display.html:
<html>
<head>
<title>API Display</title>
</head>
<body>
<h1>Weather details</h1>
<form>
{% for i in data %}
{{ country_code }}
{{ temp }}
{{ i }}
{% endfor %}
</form>
</body>
</html>
I am trying to print the values of the dictionary to html but not getting printed. The values are printing correctly in the console which means the for loop in views.py is working correctly.
Please tell me where I am wrong
You might want to make a function that handles the request for each city:
def get_city_weather(city_name):
source = urllib.request.urlopen(
'https://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
list_of_data = json.loads(source)
return {
"country_code": str(list_of_data['sys']['country']),
"coordinate": str(list_of_data['coord']['lon']) + ', '
+ str(list_of_data['coord']['lat']),
"temp": str(list_of_data['main']['temp']) + ' °C',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
'main': str(list_of_data['weather'][0]['main']),
'description': str(list_of_data['weather'][0]['description']),
'icon': list_of_data['weather'][0]['icon'],
}
Then use dict comprehension to compile the data dict to send to the template:
def display(request):
cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi']
data = {city_name: get_city_weather(city_name) for city_name in cities}
return render(request, "display.html", data)
At this point data is a dictionary who's key is the city name and who's value is the dictionary returned by get_city_weather, so it looks like (abbreviated):
{'vijayawada':
{'country_code': 'ABC'
# ...
}
# ...
}
Then in the template you could loop through this like:
{% for city_name, city_weather in data.items %}
The temperature in {{city_name}} is {{city_weather.temp}}
and the air pressure is {{city_weather.pressure}}.
{% endfor %}
Or if you don't want to specify the keys like temp and pressure, you could do:
{% for city_name, city_weather in data.items %}
<p>Weather data for {{city_name}}:</p>
<ul>
{% for k,v in city_weather.items %}
<li>{{k}}: {{v}}</li>
{% endfor %}
</ul>
<hr />
{% endfor %}
That is because you are overwriting your data dictionary. It's being passed only as one object, it should render something if you try {{data}} or {{data.country_code}}, {{data.temp}}...
One way to solve this, is to have a nested dictionary with the data of every city:
views.py
def loop_dict(request):
cities=['vijayawada','guntur','tenali','rajahmundry','amaravathi']
data = {}
for city in cities:
source = urllib.request.urlopen(
'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
list_of_data = json.loads(source)
data[city] = {
"country_code": str(list_of_data['sys']['country']),
"coordinates": {
'latitude': str(list_of_data['coord']['lat']),
'longitude': str(list_of_data['coord']['lon'])
},
"temp": str(list_of_data['main']['temp']) + ' °C',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
'main': str(list_of_data['weather'][0]['main']),
'description': str(list_of_data['weather'][0]['description']),
'icon': list_of_data['weather'][0]['icon'],
}
context = {'data': data}
return render(request, 'loop_dict.html', context)
loop_dict.html:
{% extends 'base.html' %}
{% block content %}
{% for key, obj in data.items %}
<h2>City: {{key}}</h2><br>
<p>Country Code: {{obj.country_code}}</p><br>
<p>Latitude: {{obj.coordinates.latitude}}</p><br>
<p>Longitude: {{obj.coordinates.longitude}}</p><br>
<p>Temp: {{obj.temp}}</p><br>
<hr>
{% endfor %}
{% endblock %}
AFAIK, django template system recognizes dict variable just like Python itself does.
So, if we try to convert your template code back to Python code, we would get something like this:
for i in data:
print(country_code)
print(temp)
print(i)
Now, ask yourself: will it work?
Obviously, it's not.
So, how exactly in Python you would loop and access dict values?
You can do it like this:
for i in data:
print(i)
Or with k,v loop variables (better way):
for k, v in enumerate(data):
print(f"key: {k}, value: {v}")
But, in your template code, you are trying to access certain values with the key (country_code etc).
In this case, you probably don't even need to use the for-loop.
And your display.html file can be rewritten like this:
<html>
<head>
<title>API Display</title>
</head>
<body>
<h1>Weather details</h1>
<form>
{{ data.country_code }}
{{ data.temp }}
</form>
</body>
</html>
Also, as I can see your view retrieves this data for each given city.
Thought you only pass the last one to your template.
In order to fix this, you must rewrite your view code.
I guess you could add a new variable called collected_data and then at the end of every data retrieve loop just append data to this new variable.
After that, you could just pass the collected_data to the template.
And then loop through it within the template.
But I exactly don't know how your template should look like, so I leave it to you.
I've tried to explain what's the issue is.

Laravel: Routes with parameters

I have following case:
Route::get('/kids_report_card/{id?}/{param?}', 'KidsReportCardController#index');
And in view file I have:
{{ url('kids_report_card/4') }}
In some other view file I have:
{{ url('kids_report_card/name') }} (where name is string here-some parameter)
Now the situation is:
For {{ url('kids_report_card/4') }} ,Route::get('/kids_report_card/{id?}/{param?}', 'KidsReportCardController#index'); works fine.
For {{ url('kids_report_card/name') }},Route::get('/kids_report_card/{id?}/{param?}', 'KidsReportCardController#index'); doesn't work fine as in url we have name parameter while in Route we have first parameter as id(integer value). so is there any dynamic solution that srting parameter must go to second parameter in Route??
You can pass an array of parameters in the url like this:
{{ url('kids_report_card', ['name' => 'name_value']) }}
Reference: URL's

Django: escaping translations with safe

I've got a problem. When I use HTML Tags in a translation (.po files) they end up being displayed as: <p>. When I use the |safe filter it results in <p>. But I don't get it to work that the actual html tags are passed.
Anyone got a clue about this?
.po file:
#: website/views.py:35
msgid "web_content_detailed"
msgstr "<h1>asdjkasjdlas</h1>"
view.py:
context = {}
context['somevar'] = _('web_content_detailed')
return render(request, 'somehtml.html', context)
somehtml.html:
{{ somevar }} => <h1>asdjkasjdlas</h1>
{{ somevar|safe }} => <h1>asdjkasjdlas</h1>`

Syntax for Angular expression where JSON key has an embedded blank

I am working with a trading partner who sends me JSON with embedded spaces in the keys. For example
[{"BANK ID":89769876976,"Account Number":789698769876,"Account Type":"CHECKING","Balance":1187.65...
and I cannot find a way to access the keys using angular {{ }} expressions. Any clues?
You can just use the bracket notation (without the dot)
<div ng-repeat="acct in accounts">
Bank Id: {{ acct['BANK ID'] }},
Account Number: {{ acct['Account Number'] }},
Type: {{ acct['Account Type'] }},
Balance: {{ acct.Balance }}
</div>
Here is a Demo

Django - Shorten text content retrieved in html template

I would like to know how to shorten text content retrieved to get a preview instead of getting a block of text in the html template
From: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
To:
aaaaaaaaaaaaaaaaaaaaaaaaaaa....
The code that is used to retrieve the contents is :
<a class="list_content" href="/qna/view" onclick="document.forms['q_title_{{ q.id }}'].submit(); return false" title="{{ q.content }}">{{ q.content }} </a><br/>
Many thanks!
If you are using Django 1.4, truncatechars filter will be the best way to go:
{{ q.content|truncatechars:25 }}
Assuming that "q.content" is a string you could use the slice command:
{{ q.content|slice:":255" }}
truncatechars template filter for django 1.4