How to iterate json dictionary in django template? - django

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 %}

Related

How to retrieve layout of an item using JSS

I am really new to JSS and I am very confused by the docs and how Sitecore is supposed to assemble layout information. I am trying to retrieve layout information of an item using JSS for one of our MVC project. The item in question renders fine in the browser using our traditionnal MVC stack. However I am unable to retrieve layout information of that item using JSS.
The item in question is based on the standard template and has the following presentation/layout details:
The layout points to a cshtml file.
The cshtml file contains the HTML layout, and a placeholder rendered using #Html.Sitecore().Placeholder("Menu")
The content of the placeholder is defined in Sitecore Layout Details dialog using a control/rendering named "Menu".
The rendering "Menu" points to a controller named Web.Controllers.MenuController and action named GetMenu
Content of the cshtml file:
#using Sitecore.Mvc
<main id="main" class="content group advise-area" role="main">
<div class="inner inner-carousel advise-area-content">
<div class="row">
<div class="col-2-2">
#Html.Sitecore().Placeholder("Menu")
</div>
<div class="col-2-2">
#Html.Raw(Model.Content)
</div>
</div>
</div>
</main>
When retrieving the layout information of the item using the render endpoint (/sitecore/api/layout/render/jss?item={item_id}&...). I get the fields values of the item, but I do not get any presentation details nor placeholder information.
{
"sitecore": {
"context": {
"pageEditing": false,
"site": {
"name": null
},
"pageState": "normal",
"language": "fr",
"itemPath": "/my-item"
},
"route": {
"name": "prendre-route-securite",
"displayName": "prendre-la-route-en-toute-securite",
"fields": {"Content": {"value": "My Content"}},
"databaseName": "web",
"deviceId": "fe5d7fdf-89c0-4d99-9aa3-b5fbd009c9f3",
"itemId": "85cac673-2cfb-496c-ba62-0f1d634ae241",
"itemLanguage": "fr",
"itemVersion": 1,
"layoutId": "b39337a1-8bb5-44c3-ba97-0dce8ef517f6",
"templateId": "34c34e2b-f2ac-405f-afb3-d0185bc936bb",
"templateName": "ArticleZoneConseils",
"placeholders": {}
}
}
}
The documentation says I am supposed to put some values inside the Layout Service Placeholders field of the layout. But I have no clue of what I should put in there to get the placeholder data showing in the REST query.

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,
}

Attaching metadata to array in model

I have the following model (see my previous question):
slide: {
"id": 1,
"name": "stack-overflow-page",
"type": "webpage",
"parameters": [
{"key": "url", "value": "http://stackoverflow.com"},
{"key": "extension", "value": "/questions/ask"}
]
}
Each parameter has metadata, depending on the slide type:
widget: {
"id": "webpage",
"description": "Renders a webpage.",
"parameters": [
{"key": "url", "type": "string", "description": "The base URL to show."},
{"key": "extension", "type": "string", "description": "The rest of the URL to attach, or any parameters."}
]
}
Currently, the "widget" metadata is loaded in the controller (note: ember-cli is used here):
import Ember from 'ember';
export default Ember.ObjectController.extend({
widget: function() {
return this.store.find('widget', this.get('model.type'));
}.property('model.type'),
});
However, when using the parameters in the template, I see no way to look up the metadata information for each parameter (for example, to show the parameter's description).
{{#each parameters}}
<div class="form-group">
<label class="col-sm-2">{{key}}</label>
<div class="col-sm-10">
{{input type="text" value=value class="form-control"}}
</div>
</div>
{{/each}}
Additionally, if I attached the metadata to each parameter in the model, I assume it would be sent back to the server unnecessarily, since parameters is simply a DS.attr(). Is there a good way to look up the metadata information for each parameter?
I believe the EmbeddedRecord Mixin is what you're looking for. It was just abstracted out of the Active Model serializer and added to the generic REST serializer in the most recent EmberData beta (Ember Data v1.0.0-beta.8), so you may need to upgrade to use it. You'll still need to create a DS.Model for 'parameters' with two fields 'key' and 'value' for this to serialize correctly.
You can use the extractMeta hook from the JSON or REST Serializer -> https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/json_serializer.js#L945 to parse your meta information.
If you want to access the metaData on your manyArray, you will need this patch -> https://github.com/emberjs/data/commit/8544c29419d1ef909762a50beb434c219a34c846
I completely forgot about it, I can merge it in a day or two so you don't have to edit ED yourself.

Parsing JSON in Django template

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.