why django load actually the template contents? - django

after runsrever my browser show this:**
> {% set enabled_scopes_class = 'scopes-' +
> '%s'|format(settings.ALL_SCOPE_ENABLED) + '-' +
> '%s'|format(settings.UNANSWERED_SCOPE_ENABLED) + '-' +
> '%s'|format((request.user.is_authenticated() and
> settings.FOLLOWED_SCOPE_ENABLED)) %} {# Some or all contents of this
> div may be dropped over the search bar via negative margins, to make
> sure that the search bar can occupy 100% of the content width. Search
> bar may have padding on the left and right to accomodate the buttons.
> `#}{# three buttons below are in the opposite order because they are
> floated at the right #}`
Please guide me the correct way to achieve my objective.

The reason you see the raw code when rendering the template, is that statements must be on a single line, both tags and comments.
For the multiline comments, you can use the comment tag:
{% comment %}
Some or all contents of this
div may be dropped over the search bar via negative margins, to make
sure that the search bar can occupy 100% of the content width. Search
bar may have padding on the left and right to accomodate the buttons.
three buttons below are in the opposite order because they are
floated at the right
{% endcomment %}
As for your set statement: I don't know about any set statement (is it a third-party tag?), but the template language is by design not nearly as powerful as Python code. The use of parentheses to group statements is not permitted, and you can't call functions with arguments in the same way you can do it in python. You also cannot concatenate values with + and format is not a defined template filter. I'd suggest you read up on templates in the documentation.
More advanced logic, like what you are trying to do here, should be done in the view function, and passed on to the context of the template.

You probably did not render your template
try something like:
from django.shortcuts import render
def myview(request):
return render(request, 'path/template.html', {})

Related

How can I identify tags that do not have CSS selectors with Html.Table?

I am writing a query for work for a report that has some poorly written HTML code where only some of the tags have a CSS selector I can use for creating my columns but others don't. (Guess who wrote it?) I wrote some workarounds using nth-child and describing each step to the desired tab but, as expected, when scaled up to all the other reports it causes issues because not every table is alike with what it contains.
My working code:
{"Rule ID", "td[class='rule-id']"}
However the next column I used this:
{"Time", "div[class='panel-body'] > TABLE > TBODY > TR:nth-child(6) > TD:nth-child(2)"}
Which in some of the tables does grab the time, but in others it grabs the wrong tag. I'm wondering if there's a way I can refer to the information in-between the tags. The time code looks like this:
<table>
...
<tr>
<td>Time</td>
<td>2022-04-28T10:01:15+00:00</td>
</tr>
...
</table>
I tried this but it results in a 100% empty column:
{"Time", "td[contains='Time']"}
This is my first project in Power BI so I'm learning as I go and have found answers to most of my questions through Google but I couldn't quite phrase this question properly to find a good result. All of the code is on my GFE so I can't get it over here to share, hopefully the bits I could share are enough.
Thank you in advance for your help!
If you link the site I can give a better answer.
There's an optional 3rd parameter, that gives you more access to attributes.
{"Name", "Selector"} would become {"Name", "Selector", each _ }, ex:
= Html.Table(Source,
{
{"Name", "Selector", each _ }
}
)
selector
td[contains='Time']
This isn't looking for what your html, it would match this. Here's a good reference/cheatsheet
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
<td contains='Time'>
Testing Selectors in a browser
In the web console, you can use a CSS Selector query to preview what it will select.
Firefox has shorthand using the function $ and $$ . otherwise use document.querySelector() and document.querySelectorAll()
Your RowSelector
If you were to use $$("TABLE.table > * > TR") as your RowSelector
Your columnNameSelectorPairs
And then TABLE.table > * > TR > :nth-child(1)
From:
ninmonkeys.com/Select_Tables_using_your_own_CSS_Selectors
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

Is there a Django template tag that will convert a percentage to a human readable format?

For example:
Convert 0.01 to 1%
Convert 0.001 to 0.1%
Convert 0.5 to 50%
I see in humanize there is nothing and I could not find anything in the Django documentation. I have tried {{ value|multiply:100 }}% without success. I know I can write my own template tag but I prefer to avoid doing that whenever possible.
UPDATE: I have also looked into the widthratio tag. For a value of 0.001 it goes to 0%. This is not what I want, unfortunately.
I went ahead and created a template tag filter like this:
#register.filter
def to_percent(obj, sigdigits):
if obj:
return "{0:.{sigdigits}%}".format(obj, sigdigits=sigdigits)
else: return obj
I was surprised to see the link shared in another answer didn't have a clean solution like that yet. The best one I saw used a try block instead of the if obj... I personally want to see an error in my use case, but that's up to you.
Still, good to know there isn't a more "Django" way to do it that I saw. You'd use this in your template like...
{{{{mymodel.some_percentage_field|to_percent:2}}
where 2 is the number of significant digits you want.
As Michael mentioned above, I will suggest you to write your own template tag for that : https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/
You can do this with Django built-in template tag withraatio
{% widthratio this_value max_value max_width as width %}
If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).
You can also see the details here
Maybe use one of these solutions: Is there a django template filter to display percentages?
Hope it helps. If not, write your own simple filter :)
If you only have to format a number with percent, for example "65%" :
{{ number|stringformat:"d%%" }}

String to Int --> Django

[{'age': 1}] being returned something alike to this after a query. This is in my view. Now in my HTML I want to refer to that value returned - in this case '1' if {{}} > 1 ... do something but it cannot do this because Could not parse the remainder: '{{age}}' from '{{age}}'. However if I define a random integer value in my view set it as i.e. 10 I can very easily refer to this variable in my html no problem. I'm presuming it's because it's printing'age' rather than just returning the result from the database. Any solutions to this ? I'm thinking about creating a definition which returns it into a string
You want {% if number > 2 %}. You use {{ number }} to include a variable in the template, but you don't use the double braces inside a template tag.

Sencha Touch 2 list background change

I have a list within my application, but was wondering if it is possible to have each list displayed show a different background colour, rather than the same one through out each item?
I have created a template but would be nice to have the background of each change colour.
Thanks
EDIT: I have also created the same list via a 'Ext.dataview.component.DataItem' / 'DataView' so if this is easier to control separately then great, as I am looking at interfering in te process of creating each and setting its background, if that is at all possible.
You could try to do that with simply XTemplate:
var tpl = new Ext.XTemplate(
'<p>Name: {name}</p>',
'<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
'<p>Kids: ',
'<tpl for="kids">',
'<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
'{name}',
'</div>',
'</tpl></p>'
);
take a look at their explanations, might find something interesting:
http://docs.sencha.com/touch/2-0/#!/api/Ext.XTemplate
I have seen many variants on the Ext.query('class').up().addCls('backgroundClass'); hack, which makes perfect sense to me, but my question is WHEN are people calling this? I can't put it in 'painted', since DOM doesn't seem to exist yet.. where/when are you guys executing the Ext.get(..) call?
I have been looking for this also, and I had a hard time finding out how to access the individual items of a xlist...
This is the way I finally did it:
in your itemTpl, add a class to your < div >, using the property 'id' of your model:
itemTpl:'< div class="my_list_item_{id}"> ... content ... < /div>'
the tricky part is that if you want to set the background color of the whole item area, you have to access to < div > with class 'x-item-label' that is wrapping your itemTpl < div >.
Here is how I did it (for the first item as an example):
Ext.select('.my_list_item_1').first().up('div.x-list-item-label').addCls('background_item');
where 'background_item' is a CSS style, defining your background color.
(Since there is no way (at least that I know of) to get the index count of your items in the 'itemTpl' config, I had to use to automatic 'id' property of my model/store.
Note that if you apply filtering/sorting/... on your store, this property will not be sorted anymore. So if you want to link the order displayed in your list to the 'id' property, you have to do something like 'Ext.StoreManager.get('MyStore').getAt(indexInList).get('id') )
Hope this helps...
Since Sencha Touch 2.2.1 it's also possible to use striped parameter (more info here). It will add x-list-item-odd class to odd items of your list.

Regular expression to get HTML table contents

I've stumbled on a bit of challenge here: how to get the contents of a table in HTML with the help of a regular expression. Let's say this is our table:
<table someprop=2 id="the_table" otherprop="val">
<tr>
<td>First row, first cell</td>
<td>Second cell</td>
</tr>
<tr>
<td>Second row</td>
<td>...</td>
</tr>
<tr>
<td>Another row, first cell</td>
<td>Last cell</td>
</tr>
</table>
I already found a method that works, but involves multiple regular expression to be executed in steps:
Get the right table and put it's rows in back-reference 1 (there may be more than one in the document):
<table[^>]*?id="the_table"[^>]*?>(.*?)</table>
Get the rows of the table and put the cells in back-reference 1:
<tr.*?>(.*?)</tr>
And lastly fetch the cell contents in back-reference 1:
<td.*?>(.*?)</td>
Now this is all good, but it would be infinitely more awesome to do this all using one fancy regular expression... Does someone know if this is possible?
There really isn’t a possible regex solution that works for an arbitrary number of table data and puts each cell into a separate back reference. That’s because with backreferences, you need to have a distinct open paren for each backref you want to create, and you don’t know how many cells you have.
There’s nothing wrong with using looping of one or another sort to pull out the data. For example, on the last one, in Perl it would be this, given that $tr already contains the row you need:
#td = ( $tr =~ m{<td.*?>(.*?)</td>}sg );
Now $td[0] will contain the first <td>, $td[1] will contain the second one, etc. If you wanted a two-dimensional array, you might wrap that in a loop like this to populate a new #cells variable:
our $table; # assume has full table in it
my #cells;
while(my($tr) =~ $table = m{<tr.*?>(.*?)</tr>}sg) {
push #cells, [ $tr =~ m{<td.*?>(.*?)</td>}sg ];
}
Now you can do two-dimensional addressing, allowing for $cells[0][0], etc. The outer explicit loop processes the table a row at a time, and the inner implicit loop pulls out all the cells.
That will work on the canned sample data you showed. If that’s good enough for you, then great. Use it and move on.
What Could Ever Be Wrong With That?
However, there are actually quite a few assumptions in your patterns about the contents of your data, ones I don’t know that you’re aware of. For one thing, notice how I’ve used /s so that it doesn’t get stuck on newlines.
But the main problem is that minimal matches aren’t always quite what you want here. At least, not in the general case. Sometimes they aren’t as minimal as you think, matching more than you want, and sometimes they just don’t match enough.
For example, a pattern like <i>(.*?)</i> will get more than you want if the string is:
<i>foo<i>bar</i>ness</i>
Because you will end up matching the string <i>foo<i>bar</i>.
The other common problem (and not counting the uncommon ones) is that a pattern like <tag.*?> may match too little, such as with
<img alt=">more" src="somewhere">
Now if you use a simplistic <img.*?> on that, you would only capture <img alt=">, which is of course wrong.
I think the last major remaining problem is that you have to altogether ignore certain things in parsing. The simplest demo of this embedded comments (also <script>, <style>, andCDATA`), since you could have something like
<i> some <!-- secret</i> --> stuff </i>
which will throw off something like <i>(.*?)</i>.
There are ways around all these, of course. Once you’ve done so, and it is really quite a bit of effort, you’ll find that you have built yourself a real parser, completely with a lot of auxiliary logic, not just one pattern.
Even then you are only processing well-formed input strings. Error recovery and failing softly is an entirely different art.
This answer was added before it was known the the OP needed a solution for c++...
Since using regex to parse html is technically wrong, I'll offer a better solution. You could use js to get the data and put it into a two dimensional array. I use jQuery in the example.
var data = [];
$('table tr').each(function(i, n){
var $tr = $(n);
data[i] = [];
$tr.find('td').text(function(j, text){
data[i].push(text);
});
});
jsfiddle of the example: http://jsfiddle.net/gislikonrad/twzM7/
EDIT
If you want a plain javascript way of doing this (not using jQuery), then this might be more for you:
var data = [];
var rows = document.getElementById('the_table').getElementsByTagName('tr');
for(var i = 0; i < rows.length; i++){
var d = rows[i].getElementsByTagName('td');
data[i] = [];
for(var j = 0; j < d.length; j++){
data[i].push(d[j].innerText);
}
}
Both these functions return the data the same way.