Parsing JSON in Django template - django

I want to populate the data that Im getting from Webservice - JSON response in Template.
My Service integration code:
serviceRequest = requests.get(ServiceSettings.getCitiesURL(),
headers={
"Content-Type":servicesettings.JSON_CONTENT_TYPE,
"Accept":servicesettings.HEADER_ACCEPT
})
dataJson = serviceRequest.json ()
Response that Im getting is
{"cities": [{"latitude": "21.321", "cityIdentifier": "GOOD", "cityName": "NY", "longitude": "23.23432"} , {"latitude": "1.321", "cityIdentifier": "GOOD", "cityName": "CA", "longitude": "3.23432"}
], "statusMessage": "OK", "statusCode": 200}
I'm trying to iterate it in DJango Tempalte (HTML) like below but am not not able to list the cityName
{% for objCities in cityList%}
{% for objCity in objCities.citiess%}
{{objCity.cityName}}
{% endfor%}
{% endfor%}

In your loop, you were trying to access a string with an index. So TypeError: string indices must be integers, not str was raised.
Consider following:
{% for objCity in cityList.cities %}
{{objCity.cityName}}
{% endfor%}
This will work.

Related

How to convert Django datetime to HighCharts format

I am trying to display datetime on a chart but having some trouble as it seems to be putting out an odd format to the chart.
Django template:
var employeeLastLoginWithPoints = [
{% for employee in employee_list %}
[{{ employee.last_login|date:"SHORT_DATE_FORMAT" }}, {{ employee.points }}]
{% if not forloop.last %}, {% endif %}{% endfor %}
];
Highcharts snippet:
xAxis: {
type: "datetime",
dateTimeLabelFormats: {
day: '%b/%d/%Y'
},
What the chart looks like:
All the date data is pushed to the left at Jan/01/1970
Sources/Index of the DOM:
var employeeLastLoginWithPoints = [
[01/11/2020, 0]
,
[01/07/2020, 3]
,
[01/11/2020, 14]
,
[01/08/2020, 8]
];
console.log(employeeLastLoginWithPoints):
(4) [Array(2), Array(2), Array(2), Array(2)]
0: (2) [0.000045004500450045, 0]
1: (2) [0.00007072135785007072, 3]
2: (2) [0.000045004500450045, 14]
3: (2) [0.00006188118811881188, 8]
Why is the console log showing up different and how do I get it to display correctly?
Thanks in advance!
You need to wrap the rendered date in quotes,
["{{ employee.last_login|date:"SHORT_DATE_FORMAT" }}", {{ employee.points }}]
At the moment you are rendering 01/11/2020 as one of the values, this is being interpreted as the calculation 01 / 11 / 2020 which returns a float

Ansible and Template file inserting values in to the template

I'm having issues at the moment I have a map of some aws subnets with their routing tables like so ( example output via ansible) :
"subnetwork_route_map": [
{
"route_table_id": "rtb-xxxxxx",
"subnet_id": "subnet-xxxxxx"
},
{
"route_table_id": "rtb-xxxxxx",
"subnet_id": "subnet-xxxxxxx"
},
{
"route_table_id": "rtb-xxxxxx",
"subnet_id": "subnet-xxxxxx"
}
]
I wish to insert these values in to a template file and I thought I could do something like this after seeing a few example:
{% for item in subnetwork_route_map %}
{{ item[1]['subnet_id'] }},{{ item[1]['route_table_id'] }}§
{% endfor %}
how ever i'm getting an error when I try this I get an error from ansible:
fatal: [localhost]: FAILED! => {"failed": true, "msg": "dict object has no element 1"}
subnetwork_route_map is a list of dictionaries, item is an individual dictionary, you don't need the [1] part:
{% for item in subnetwork_route_map %}
{{ item['subnet_id'] }},{{ item['route_table_id'] }}§
{% endfor %}

Django CMS manage placeholder in template pages

I would enjoy your help on two points :
First, I am creating some default page's templates like :
"Home.html, work-with-us.html" etc.
My aim is to simplify the work of people who will be in charge of the website. They don't have to learn how to manage plugin inside placeholder.
Thus, I created some placeholder like this , example for "workwithus.html" :
{% extends "base.html" %}
{% load cms_tags staticfiles sekizai_tags menu_tags %}
{% block content %}
<div class="container">
<div class="col-xs-12">
{% placeholder "image-full" %}
</div>
<div class="col-md-12">
{% placeholder "text-platform" %}
</div>
</div>
{% endblock content %}
And I managed the plugins this way :
CMS_PLACEHOLDER_CONF = {
'image-full': {
'plugins': ['FilerImagePlugin'],
'name': gettext("Image full page"),
'default_plugins': [
{
'plugin_type': 'FilerImagePlugin',
'values': {
},
},
],
'limits': {
'global': 1,
'FilerImagePlugin': 1,
},
},
etc
The problem is that, I can't use multiple time the same placeholder in the same template. It would be so nice if, when I make a placeholder "img-full-width" I could be able to call it several times.
Do you have any idea about it ? A way to make it more proper than creating "img-full-2", "img-full-3" etc.
Second question :
Is it possible to add more than one default_plugins ? It really annoy me...
Thank you very much in advance guys !
You can have as many plugins as you like as default_plugins
See http://django-cms.readthedocs.org/en/support-3.0.x/reference/configuration.html#placeholder-default-plugins
You can specify the list of default plugins which will be
automagically added when the placeholder will be created (or
rendered).
If you are annoyed with having to redefine CMS_PLACEHOLDER_CONF for each placeholder, you can always define a common config before the CMS_PLACEHOLDER_CONF block:
img_fullwidth_conf = {
'plugins': ['FilerImagePlugin', 'TextPlugin'],
'name': gettext("Image full page"),
'default_plugins': [
{
'plugin_type': 'FilerImagePlugin',
'values': {
},
},
{
'plugin_type': 'TextPlugin',
'values': {
'body': '<p>Write here...</p>'
},
},
],
}
CMS_PLACEHOLDER_CONF = {
'img-full-1': img_fullwidth_conf,
'img-full-2': img_fullwidth_conf,
'img-full-3': img_fullwidth_conf,
}

How to get django_hitcount app working with Mezzanine blog

Been trying for several hours now.
I set up according to instructions but I can't get it to count hits on a blog post.
/blog/blog_post_detail.html
{% load .. .. .. hitcount_tags %}
.
.
.
.
{% block blog_post_detail_content %}
<script type="text/javascript">
$(document).ready(function() {
{% get_hit_count_javascript for blog_post %}
});
</script>
{% get_hit_count for blog_post %}
.
.
.
{% endblock %}
And in my urls.py I added:
url(r'^blog/ajax/hit/$', update_hit_count_ajax, name='hitcount_update_ajax'),
Looking at page source in browser the javascript does appear to run.
$(document).ready(function() {
var csrf = $('input[name=csrfmiddlewaretoken]').val();
$.post( '/blog/ajax/hit/',
{ csrfmiddlewaretoken: csrf, hitcount_pk : '1' },
function(data, status) {
if (data.status == 'error') {
// do something for error?
}
},
'json');
});
But it's not counting. So I'm not quite sure why it doesn't count a page hit.
Figured it out. In Mezzanine you have to put custom url patterns above the
("^", include("mezzanine.urls")),
pattern otherwise they will be ignored.

How to iterate json dictionary in django template?

I am new in django and now i am trying to iterate one json dictionary in html page. I am using the {{context}} for displaying the dictionary which is passed from the view and context is the variable used to store the dictionary in render_to_response. now it is diplayed like
[
{
"pk": 5,
"model": "Auction.newauction",
"fields": {
"username": 1,
"category": "furniture",
"description": "Made of Wood",
"end_date": "2012-05-01 11:00:00",
"start_price": "100",
"title": "Table",
"start_date": "2012-03-04 11:24:11"
}
}
]
How I can iterate this dictionary to display like
username : 1
category : Furniture
Can anyone please help me
You shouldn't "convert it to JSON" unless you're planning to have your logic in Javascript. Instead, in your template you could iterate over the array in a for loop and traverse the dictionary to the username and category keys:
{% for c in context %}
<div>username: {{ c.fields.username }}</div>
<div>category: {{ c.fields.category }}</div>
{% endfor %}