django __unicode__() - how can i call this method in a template - django-models

I defined a unicode() method in my Contact model.
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
Now I want to show the return value of the unicode() method in a template.
But all that i try fails.
{{ object.unicode }}
or
{{ object.unicode() }}
or
{{ object.__unicode__ }}
or
{{ object.str }}
That confuses me since I have another Model level function which can be referenced to from the template without problems.
This works fine:
def get_id(self):
return "%i" % self.id
{{ object.get_id|escape }}

{{ object }}
Will automatically return the value of __unicode__ for any object.

Related

Laravel ->with() can't be shown in blade (Undefined property)

I'm trying to pass an article from my controller to my view using laravel 5.3
if I just use {{ $selectedArticle }} I get the full output :
[{"id":5,"title":"Up up and awayy",
"link":"www.google.be",
"points":0,
"userID":1,
"isDeleted":"FALSE",
"created_at":"2017-01-25 23:53:19",
"updated_at":"2017-01-25 23:53:56"
}]
But when I try using $selectedArticle->id I get the following error:
Undefined property: Illuminate\Support\Collection::$id
How can I call on the properties of the article separatly? (call the id, title,... )
My controller code:
public function index($id)
{
$comments = DB::table('comments')->orderBy('id')->where(['artikelID' => $id, 'isDeleted' => 'FALSE'])->get();
$article = DB::table('articles')->orderBy('id')->where(['id'=> $id])->get();
return view('comments.comments')
->with('storedComments', $comments)
->with('artikelid',$id)
->with('selectedArticle', $article);
}
The variable you're passing to the view is an array and to display the value you should loop through the array like this.
#foreach($selectedArticle as $article)
{{ $article->id }}
#endforeach
Or if you'd like to select only one object using first() function to get the first row, like this:
$article = DB::table('articles')->orderBy('id')->where(['id'=> $id])->first();

Difference between {{ url('/task') }} and {{ url ()/task}}?

Hi i am using Laravel 5 on a previous project while writing blade template i used the form action as
<form action="{{ url() }}/task" method="POST" class="form-horizontal">
But in my recent project i am using the same format but the code is giving error
Htmlentities()expect parameter 1 to be string object given.
If i write like this
<form action="{{ url('/task') }}" method="POST" class="form-horizontal">
the code is working can any one help me understand the difference and how can i fix it
url() is a helper function. It returns a fully qualified URL to a given path (a string) or an instance of Illuminate\Routing\UrlGenerator class (an object). You can see how it works out there - src/Illuminate/Foundation/helpers.php
So, when you run {{ url() }} in your template you simply ask template engine to apply a htmlentities function to an object.
Prior to Laravel 5.2 (in 5.1 and less) the url() helper function always returns a string:
function url($path = null, $parameters = [], $secure = null)
{
return app(UrlGenerator::class)->to($path, $parameters, $secure);
}
Now, they handle if a first parameter is null
function url($path = null, $parameters = [], $secure = null)
{
if (is_null($path)) {
return app(UrlGenerator::class);
}
return app(UrlGenerator::class)->to($path, $parameters, $secure);
}

AngularJS orderBy expression with subtraction

I have an expression
{{ product.SelectedProduct.BasePrice - product.SelectedProduct.Discount | currency }}
I need to be able to order my products by the value of baseprice - discount. Is there a way to do this? So I want something like
{{product.SelectedProduct.ProductName |
orderBy : product.SelectedProduct.BasePrice - product.SelectedProduct.Discount }}
New code:
<div class="row-fluid">
<span class="mktpl_productnm" ng-show="product.SelectedProduct.ProductName">{{product.SelectedProduct.ProductName || 'product not available' | orderBy: price }}</span>
<span ng-hide="product.SelectedProduct.ProductName" class="field-validation-error">Product not available</span>
<span ng-show="product.SelectedProduct.remaining < product.SelectedProduct.prodterm.minQuantity" class="field-validation-error">
(Out of stock)
</span>
</div>
vm.price = function (product) {
debugger;
return product.SelectedProduct.BasePrice - product.SelectedProduct.Discount;
};
First of all, your example doesn't make much sense: orderBy applies to an array, to order the elements of this array. But product.SelectedProduct.ProductName is probably not an array.
Second: the documentation says:
expression function()stringArray.<(function()|string)>=
A predicate to be used by the comparator to determine the order of elements.
Can be one of:
function: Getter function. The result of this function will be sorted using the <, ===, > operator.
[...]
So, all you need is a function in the scope that returns the element to compare for a given element of the array:
$scope.reducedPrice = function(product) {
return product.SelectedProduct.BasePrice - product.SelectedProduct.Discount;
};
and in the view:
{{ productArray | orderBy:reducedPrice }}
Another option would be to precompute the reducedPrice and store it as an attribute or the product, and then simply use
{{ productArray | orderBy:'reducedPrice' }}

Date format in AngularJS and Symfony

I'm trying to display a date in the format "dd/mm/yyyy" in AngularJS. I'm retrieving data from database with symfony2.
When I inspect my scope in the browser it looks like I have a valid date object:
CreationDate : Object { date="2014-05-15 00:00:00", timezone_type=3, timezone="Europe/Paris"}
Here is what i have tried:
{{res.creationDate | date:'dd/MM/yyyy' }}
which prints this:
{"date":"2014-08-12 00:00:00","timezone_type":3,"timezone":"Europe/Paris"}
and quite logically:
{{res.creationDate.date }} --> 2014-05-15 00:00:00`
I'd like to have "15-05-2014"
---- EDIT
My controller:
public function ViewAction()
{
$repository = $this->getDoctrine()->getManager()->getRepository('AcmeMyBundle:MyEntity');
$list = $repository->getArray();
$list = json_encode($list);
return $this->render('AcmeMyBundle:Search:search.html.twig', array('list' => $list) );
}
My custom getArray function in repo:
public function getArray()
{
$query = $this->createQueryBuilder('s');
return $query->getQuery()->getArrayResult();
}
My template looks something like this:
<div class="col-md-10 col-md-offset-1" ng-init= "result= {{list}}">
<ul class="list-group">
<div ng-repeat="res in result | filter:searchText | filter:nom | filter :prenom | limitTo:50 " >
<li class="list-group-item">Date {% verbatim %} {{res.creationDate | date:'dd/MM/yyyy' }} {% endverbatim %}</li>
</div>
</ul>
creationDate is a "date" format, in a SQL Database. In phpmyadmin it prints 'dd-mm-yyy'
If you can alter the date object from date="2014-05-15 00:00:00" to date="2014-05-15T00:00:00" it should work.
Working example at this JSFiddle
You might also want to take a look on this post about JSON date format
If you try to format the date directly?
{{res.creationDate.date | date:'dd/MM/yyyy' }}
If anyone wondering..
Here is a trick i came up with for my problem
view
{{ mySplit(res.symfonyDateObject.date, 0) | date:'dd-MM-yyyy' }}
controller
app.controller('SearchController', function($scope)
{
$scope.mySplit = function(string, nb) {
$scope.array = string.split(' ');
return $scope.array[nb];
}
});
tldr i split the string in half, remove the hh/mm/ss and then angular format works
You can use javascript Date object to convert your timestamp(2014-05-15 00:00:00) into a time string(1400092200000) and apply angular filter
Working example at this JSFiddle

Google App Engine: Outputting 'values' from a SearchResult object on Jinja2 template.

I would like to return the field values of a SearchDocument's object. For example, I have generated a SearchResult object using:
class SearchResult(Handler):
def get(self):
index = search.Index("INDEX_NAME")
results = index.search("Brian")
self.render('search-result.html', results = results)
The results object looks something like this:
search.SearchResults(results=[
search.ScoredDocument(
doc_id=u'6122080743456768',
fields=[search.TextField(name=u'full_name', value=u"Brian Jones"),
language=u'en',
rank=106509239L),
search.ScoredDocument(
doc_id=u'4714705859903488',
fields=[search.TextField(name=u'full_name', value=u"Brian Lara"),
language=u'en',
rank=106427057L)],
number_found=2L)
Inside search-result.html, how can I return the values of the fields?
...
<body>
{{ field_values }} #return the field values "Brian Lara" and "Brian Jones"
<body>
...
Start here:
{% for result in results %}
{{ result.fields[0].value }}
{% endfor %}
(You have a '[' mismatch in your fields. Fix that, then check the syntax)

Resources