I currently have a date that is formatted in unicode:
k = u'2015-02-01'
I tried to add this to a list and change it into a string:
date = []
date.append(str(k))
Then I want to pass this as a Django context to my template.
However, the date is showing up with the following:
'2015-02-01'
How do I just rid of $#39; and replace it with a double quote (")?
Thanks much.
You can try to prevent string escape in template like this:
{{ variable|safe }}
In-view way:
from django.utils.safestring import mark_safe
from django.template import Context
data=mark_safe(data)
inescapable = Context({'data': data}, autoescape=False)
I know this is old but other people might stumble upon this with the same problem
Try
{% autoscape off %} {{ date }} {% endautoscape %}
It worked fine for me
When requesting graphs from google charts the data must be sent as a text array. The csv file has to be pure text with no apostrophes.
however
code fragment
data = repr(textData)
returns data bounded by ' '
this is interpreted as "'" in html
The solution to this is to javascript split method
var par = textData.split(""'") textArray = par[1] // the part without '
rest of code
Related
in my sql table I have decimal data with dot as a separator but the display in my page is done with commas
I would like to display them with dot
in my settings i have this
LANGUAGE_CODE = "fr-fr"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
my models
class VilleStation(models.Model):
nomVille = models.CharField(max_length=255)
adresse = models.CharField(max_length=255)
cp = models.CharField(max_length=5)
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
in the templates i have this
{% for c in object_list %}
{{c.nomVille}}
{{c.adresse}}
{{c.cp}}
{{c.latitude}}
{{c.longitude}}
{% endfor %}
thank
Give this a whirl, as per the docs, you can turn off number localisation like so:
{{ value|floatformat:"3u" }}
What do the docs say?
Output is always localized (independently of the {% localize off %} tag) unless the argument passed to floatformat has the u suffix, which will force disabling localization.
Be aware of the following note further down the page:
Changed in Django 4.0:
floatformat template filter no longer depends on the USE_L10N setting and always returns localized output.
And subsequently:
The u suffix to force disabling localization was added
Please see the documentation regarding the floatformat template tag
Decimal separator is controlled by two settings in Django settings:
First one is DECIMAL_SEPARATOR (Default: '.')
https://docs.djangoproject.com/en/4.1/ref/settings/#decimal-separator
And second one: USE_L10N (Default: True)
https://docs.djangoproject.com/en/4.1/ref/settings/#use-l10n
in your case use USE_L10N=False
i want to generate a list of ip addresses (using range of last 8bits so 120-190 translates to x.x.x.120 - x.x.x.190) in defaults/main.yml in my role, and later use it to create new network interfaces and generate a new config file. I tried this approach:
defaults/main.yml:
ip_list: "{%for address_end in range(50,99)%} 192.168.0.{{address_end}}{%endfor%}"
conf_list: "{%for ip in ip_list%}server {{ip}}:6666 {%endfor%}"
and then to use it in template
template.conf.j2:
{% for conf_line in conf_list %}
{{conf_line}}
{% endfor %}
and all i got in generated config file was:
s
e
r
v
e
r
:
6
6
6
6
s
e
r
v
e
r
1
:
6
so my guess is that i'm not generating a list but just a long string and when I use for loop in template.conf.j2 I iterate over single chars. I tried using answer to this problem but all i got was syntax error. Any ideas for what might help me ?
You should format your vars as JSON lists if you want them to be lists.
1.1.1.1 2.2.2.2 3.3.3.3 is a string.
['1.1.1.1', '2.2.2.2', '3.3.3.3'] will be converted to list.
But there is alternative approach for you:
ip_list: "{{ lookup('sequence', 'start=50 count=12 format=192.168.0.%d', wantlist=True) }}"
conf_list: "{{ ip_list | map('regex_replace','(.*)','server \\1:6666') | list }}"
Kostantin answer was of much help, but i found just realized that generating config entries in my case could be solved in an less complex way. Instead of trying to iterate over list or a string variable variable in jinja template file template.conf.j2 like did with :
{% for conf_line in conf_list %}
{{conf_line}}
{% endfor %}
you could just enter insert new line signs while generating string in defaults/main.yml:
conf_list: "{%for ip in ip_list%}server {{ip}}:6666\n{%endfor%}"
and then just insert that whole string into a template.conf.j2 like this:
{{conf_line}}
nevertheless i have no other idea how to generate list of ip addresses other than the one Konstantin proposed.
My variable is as such:
api-20150901r1_6.38
Using Jinja, I need a way to grab the string BEFORE the hyphen. There will always be one hyphen so I dont need to worry about multiple instances.
Assuming input_string is api-20150901r1_6.38
You can use set
{% set mylist = input_string.split('-') %}
This is your value "api" in this case
{{ mylist[0] }}
I have a bunch of pandas dataframes in a list that I need to convert to html tables. The html code for each individual dataframe looks good, however when I append the html to a list I end up with a bunch of \n characters showing on my webpage. Can anyone tell me how to get rid of them?
python code:
dataframe_html = []
table_dic = {}
for df in dataframes:
frame = df.to_html(classes="table table-hover")
dataframe_html.append(frame) #this is the line where all the \n get added
table_dic.update({'dataframe_html':dataframe_html})
return render(request,'InterfaceApp/FileProcessor_results.html',table_dic)
html code:
<div class="table-responsive">
{{ dataframe_html | safe }}
</div>
Shows up like this:
'
Can anyone help me out with this??
To display 3 separate tables, join the list of HTML strings into a single string:
dataframe_html = u''.join(dataframe_html)
for df in dataframes:
frame = df.to_html(classes="table table-hover")
dataframe_html.append(frame)
dataframe_html = u''.join(dataframe_html)
table_dic = {'dataframe_html':dataframe_html}
return render(request,'InterfaceApp/FileProcessor_results.html',table_dic)
FWIW this late in the game:
I had originally had:
response = render_template('table_display.html', query_results=[df_html], query_name='Quality Item Query')
and was getting an entire row of \n characters. Changed to below and the newlines disappeared.
response = render_template('table_display.html', query_results=df_html, query_name='Quality Item Query')
Even later in the game...
I stumbled upon this thread when having the same problem. Hopefully, the below helps someone.
I assigned the results of df.to_html() to a (nested) list and got the new lines when rendering in my Jinja template. The solution inspired by #AlliDeacon was to index the result again when rendering
Python code:
result[0][0] = df.to_html()
Jinja template:
<div>Table: {{ result[0][0][0] }}</div>
Refer output of the following code for illustration of the difference between a (sub-)list and a list element:
df = pd.DataFrame([['a','b']],
columns=['col_A', 'col_B'])
tmp = []
tmp.append(df.to_html(index=False))
print(tmp)
print(tmp[0])
Result:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>col_A</th>
<th>col_B</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>
Even more than late than late to the game. The issue with the newline characters is that the frame is by default in JSON when passed from your app to Jinja. The \n's are being read literally, but the table gets constructed from what follows inside the JSON string. There are two cases to deal with this, depending on the method of passing your dataframe:
Case 1: Passing a dataframe with render_template:
Pass the frame in your app without the "df.to_html". Within your html use the Jinja2 syntax to obtain a clean frame without any newline characters:
{{ df_html.to_html(classes="your-fancy-table-class") | safe }}
Case 2: Passing with json.dumps to be retrieved in JS
In case you send your frame via a response, e.g. post Ajax request, pass the frame with df.to_html() as you did:
#app.route('/foo', methods=['POST']) #load and return the frame route
def foo():
# df = pd.DataFrame...
return json.dumps({"response": df.to_html}
Then in your JS, load the clean frame without the newline characters in HTML from your response with:
JSON.parse(data).response;
$("#your-table-wrapper").html(response);
I'm using Google app engine and I'm trying to set the value of a textarea based on the concatenation of two string variables. Let's say I have 4 items, and each item has multiple fields. So in my Python I'm passing the dictionary { 'value0': newValue }. I'm using a for loop (iterator value num) and I want to use in my HTML something equivalent to {{ value }}{{ num }} where the variable referenced is value0.
I've tried {{ value~num }} but nothing works. If I could use an array that would be even better - such as {{ value[num] }}