Accessing JSON Key with Colon in Django Template - django

I'm trying to access the id field in JSON in a Django template, but it has a colon in it.
When I include it in the template, I get the following error:
"Could not parse the remainder: ':id' from 'result.id.attributes.im:id'".
I've tried escaping the name and the colon with no success.
I've included the JSON output when I use it's parent, as well as the Django template.
Any suggestions?
*HTML Output with JSON when passing up the parent (result.id.attribute) *
1 id: {**u'im:id': u'422689480'**, u'im:bundleId': u'com.google.Gmail'} Name: Gmail - Google, Inc.
2 id: {u'im:id': u'530755375', u'im:bundleId': u'com.kfactormedia.mycalendarfree'} Name: MyCalendar Free - K-Factor Media, LLC.
3 id: {u'im:id': u'518972315', u'im:bundleId': u'com.click2mobile.textGramFree'} Name: Textgram - Texting with Instagram FREE - click2mobile
4 id: {u'im:id': u'521863802', u'im:bundleId': u'com.appmosys.emoji2free'} Name: Emoji 2 Free - 300+ NEW Emoticons and Symbols - Appmosys
Django Template
<html>
<body>
{% for result in app_data.entry %}
<h3>
{{ forloop.counter }}
Id: {{ result.id.attributes }}
Name: {{ result.title.label }}
{% endfor %}
</h3>
</body>
</html>
Edit to include the View:
View
def findAppRank(request,AppId=424909112):
URL="http://itunes.apple.com/us/rss/topfreeapplications/limit=300/genre=6007/json"
r=requests.get(URL)
output=r.content
data=json.loads(output)
AppData=data['feed']
t=get_template('myrank.html')
html=t.render(Context({'app_data': AppData, 'app_id': AppId }))
return HttpResponse(html)

You're looking for the slice filter.
{{ result.id.attributes|slice:"'im:id'" }}

Related

How to access custom fields in a data.home._children loop

I've added a few custom fields in lib/modules/apostrophe-custom-pages/index.js
Specifically, I've added a field for an excerpt, image Singleton for a cover image and another Singleton that will allow users to define an icon to a page.
This is how these images are defined:
{
name: 'icon',
label: 'Icon',
type: 'singleton',
widgetType: 'apostrophe-images',
options:{
limit: 1,
minSize: [200,200],
aspectRatio: [1,1],
},
controls:{
movable:false
},
image: true
},
{
name: 'coverimg',
label: 'Header Image',
type: 'singleton',
widgetType: 'apostrophe-images',
options:{
limit: 1,
minSize: [400,400],
aspectRatio: [1,1],
},
controls:{
movable:false
},
image: true
}
The cover image and the icon I can retrieve while on the page by using: {% set coverimage = apos.images.first(data.page.coverimg) or null %} ,
however, I can't reach the icon in the navigation under data.home._children like so:
{%- for tab in data.home._children -%}
{%- set iconImg = apos.images.all(tab.icon) %}
{{ apos.log(tab) }}
<li>
<a class="sidebar-main-link
{% if data.page and (apos.pages.isAncestorOf(tab, data.page) or tab._id == data.page._id) %}
active
{% endif %}
" href="{{ tab.slug }}">
<div class="icon" style="
backgroung-image: url('{{ apos.attachments.url(image.attachment, { size: 'full'}) }}') "></div>
{{ tab.title }}
</a>
</li>
{% endfor %}
This returns the standard missing.svg image
There is a new tutorial on the apostrophe documentation site which covers this issue in detail.
The short answer is that you must configure the filters option of the apostrophe-pages module to load related pages with more than just very basic information. For performance reasons, this default behavior is not a bad thing, but asking Apostrophe to load just one widget won't slow things down too much.
// in lib/modules/apostrophe-pages/index.js
module.exports = {
// other configuration, then...
filters: {
ancestors: {
children: {
areas: [ 'thumbnail' ]
}
}
}
};

Trying to access Django REST API in Angular2

I am working on a project where we use Angular2 and a Django backend that has a rest API. Right now we are simply just trying to get the django backend to send JSON objects to Angular2. For some reason when we make get requests, it comes back as blank. Right now we just have dummy test functions, but even those don't work.
/_services/user.service.ts
tempFunc() {
return this.http.get('http://localhost:8000/chains/', this.jwt()).map((model: Response) => model.json());
}
/temptemp-page.component.ts
import { Router } from '#angular/router';
import { UserService } from '../_services/user.service';
export class Temp {
name : string;
description : string;
slogan : string;
founded_date : string;
website : string;
}
#Component({
selector: 'app-temp-page',
templateUrl: './temp-page.component.html',
styleUrls: ['./temp-page.component.css']
})
export class TempPageComponent implements OnInit {
model: Temp;
constructor(
private router: Router,
private userService: UserService) { }
ngOnInit() {
this.model = {
name: 'Wrong',
description: 'Wrong',
slogan: 'Wrong',
founded_date: 'Wrong',
website: 'Wrong',
}
this.userService.tempFunc().subscribe(model => this.model = model);
console.log(this.model);
}
}
The Wrong is there just to know that if we get nothing, it will print Wrong and we know the get request isn't succeeding.
temp-page-componenent.html
<div style="margin-left: 20px;">
name: {{ this.model.name }} <br/>
description: {{ this.model.description }} <br/>
slogan: {{ this.model.slogan }} <br/>
founded_date: {{ this.model.founded_date }} <br/>
website: {{ this.model.website }} <br/>
<hr/>
</div>
The django backend has a model with field of the type above in this html file, in a table called Chains. at that URL specified. For some reason, every attempt to call it works. Except for Angular2, and I am asking this to figure out if there is just bad syntax, or something else related to the problem. I know it works because when I do
curl -g localhost:8000/chains/
It works fine and returns
[{"name":"Cafe Amazing","description":"Founded to serve the best sandwiches.","slogan":"The best cafe in the Mississippi!","founded_date":"2014-12-04T20:55:17Z","website":"http://www.thecafeamazing.com"}]
with a sucess code on the django server of 200 204.
However when I try the angular2 code above it returns the same codes but nothing gets displayed. What am I doing wrong here?
don't use this in your template use only the property name, like this :
<div style="margin-left: 20px;">
name: {{ model.name }} <br/>
description: {{ model.description }} <br/>
slogan: {{ model.slogan }} <br/>
founded_date: {{ model.founded_date }} <br/>
website: {{ model.website }} <br/>
<hr/>
</div>
you tempFunc is asynchronous so console.log(this.model) will be executed first :
this.userService.tempFunc().subscribe(model => this.model = model);
console.log(this.model);
do this :
this.userService
.tempFunc()
.subscribe(model =>{
this.model = model
console.log(this.model);
});

Dynamic model name for ng-repeat in angularjs

I am using angularjs with django. In my html page, I am doing the following:
<div ng-repeat="loc in locations" ng-init="locIndex = $index" ng-show="tab===1">
Id: {[{loc[0]}]}
Location Name: {[{loc[1]}]
</div>
Now, what I am interested in doing is:
<div ng-repeat="loc in locations" ng-show="tab===1">
Id: {[{loc[0]}]}
Location Name: {[{loc[1]}]
</div>
<div ng-repeat="cloc in childLocation{[{loc[0]}]}">
Child Id:{[{loc[0]}]}
Child Location Name: {[{loc[1]}]
</div>
In app.js, i will initialize the childlocations when the user will click the parent location
$scope.getChildLocations=function(locationId){
$http({
method: "get",
url: '/get_child_locations?locationId='+locationId,
}).success(function(data, status) {
childLocation='childLocation'+location
$scope.childLocation=data;
});
}
Is it possible to do this. If yes, how as i am getting an error in this..
You are getting an error because loc is not defined in your second ng-repeat since it is not nested.
Try:
<div ng-repeat="loc in locations" ng-show="tab===1">
Id: {[{loc[0]}]}
Location Name: {[{loc[1]}]
<div ng-repeat="cloc in childLocation{[{loc[0]}]}">
Child Id:{[{loc[0]}]}
Child Location Name: {[{loc[1]}]
</div>
</div>

How do I use the Django for template tag in Dojo?

I am trying to use the "for" Django template tag in my javascript. Iam using Dojo's DataGrid to create a list of items. This is my code:
<script type="text/javascript">
require(['dojox/grid/DataGrid' , 'dojo/data/ItemFileWriteStore' , 'dojo/dom' , 'dojo/domReady!'],
function(DataGrid, ItemFileWriteStore, dom){
/*set up data store*/
var data = {
identifier: "id",
items: []
};
{% for item in items_list %}
data.items.push({ id: {{ item.url }} + '_' + {{ item.id }}, col1: {{ item.description }} });
{% endfor %}
var store = new ItemFileWriteStore({data: data});
/*set up layout*/
var layout = [[
{'name': 'Description', 'field': 'id', 'width': '100px'}
]];
/*create a new grid*/
var grid = new DataGrid({
id: 'grid',
store: store,
structure: layout,
rowSelector: '20px'
}, "grid");
/*Call startup() to render the grid*/
grid.startup();
});
</script>
However, when I go to my webpage, I get this error:
Uncaught SyntaxError: Unexpected identifier
What am I doing wrong and how do I fix it? Thanks!
You need to add quotes around the values in the dictionary
data.items.push({ id: '{{ item.url }}_{{ item.id }}', col1: '{{ item.description }}' });

ember-data isValid, isSaving and isError

I have a simple ember-data model:
WZ.Exercise = DS.Model.extend
name: DS.attr 'string'
description: DS.attr 'string'
group: DS.belongsTo 'WZ.Group'
I want to display a confirmation message to the user if a new record has been saved or if an error has occurred. The error could be that the the object is invalid and an error json is returned like below:
{"errors":{"description":["can't be blank"]}}
I can see that each model comes with an isSaving, isValid property and an isError property.
Can anybody tell me how I can use these properties to display the correct notifications to the users?
I can't help you with the validations part, but if you want to display information to the user based on the state of the data you can use these status in your view template like so:
{{#if content.isNew }}
<button {{ action save }} >Save</button>
{{/if}}
{{#if content.isSaving }}
<i>Saving record...</i>
{{/if }}
{{#if content.isLoaded }}
<b>Record created</b>
{{/if }}
{{#unless content.isValid }}
<error>Error saving data</error>
{{/unless }}
Additional to sly7_7's first link (adding the ObserverSaveOnce function to DS.Model), you could patch the RESTadapter to catch the server-side error messages.
An example implementation you can find here: https://gist.github.com/3981832
(I did not paste the code here because I may update the gist for newer versions of ember-data)