Removing an apostrophe from a Django Jinja Template? - django

I would like to remove an apostrophe from a Django template variable in HTML using Jinja.
The variable item.product is Paul's Phone which I am using to open a Boostrap Modal:
id="move_{{ item.product|cut:' ' }}"
This will remove the spaces, which is good. The outcome now is Paul'sPhone, but I can't remove the apostrophe by doing this:
data-target="#move_{{ item.product|cut:' ', ''' }}"
How do I get around these tags to remove the apostrophe from that variable?

The best way around this is to not forget Django has already set up everything with an "ID".
Just use data-target="#move_{{ item.id }}"
this was my gift of rookie error to you!

Related

Escape single curly brace in Django template

I am looking to generate a string like \usepackage{mypackage} from a Django template.
Suppose there is a variable package.name in the context how can I generate this?
Firstly I tried, \usepackage{{{package.name}}} but that throws TemplateSyntaxError
Then I tried \usepackage{ {{package.name}} } which works but has the two spaces in the output, ie, \usepackage{ mypackage }
Is there an easy way to generate this string with Django template engine?
You can also print strings with the mustache-syntax e.g.: {{ 'random string' }}. So we can print the corresponding curly brace like this:
\usepackage{{ '{' }}{{ package.name }}{{ '}' }}
Output:
\usepackage{mypackage}
You can do something like this using span
\usepackage{<span>{{package.name}}</span>}
one option is that you can write a template tag that will render it as you want and give the package name as a variable

How to add date-time arguments to django URL tag

I am trying to get this URL in my template.
path('show_date/<int:year>/<int:month>/<int:date>/',show_date,name='show_date'),
My template
<a href="{%url 'diary:show_date'{{date|date:'Y'}} {{date|date:'m'}} {{date|date:'j'}}
%}">{{date}}</a>
returns this error
Could not parse some characters: 'diary:show_date'|{{date||date:'Y'}}
Please help me fix this issue
You shouldn't add the double braces when you use a filter on a variable in a tag, you can use the filters without them
{{ date }}

Trying to render a django form field as a variable in a script tag in an html template, but the javascript isn't working

My issue is simple enough--I am trying to render a form field from a django form into a javascript variable, defined within a <script> tag, within a django template.
When I output a CharField, there's no problem. But when I try to render a ChoiceField, the resulting output breaks the html, and prevents the script tag from correctly parsing my variable.
To demonstrate my setup, I have a form defined in forms.py, exactly like this example form:
from django import forms
form = TestForm(forms.Form):
testfield = forms.ChoiceField(initial="increase_rate",
choices=[
("a", "option a"),
("b", "option b"),
("c", "option c"),
("d", "option d")
])
I am instantiating the form in views.py, and passing it into a django template to be rendered.
from django.shortcuts import render
from .forms import TestForm
[...]
#require_http_methods(["GET"])
def webpage(request):
form = TestForm()
return render(request, 'index.html', {"form":form})
Then, finally, in my template, I have something like the following:
[...]
<script>
window.testfield = '{{ form.testfield }}'
</script>
[...]
Up until this point, everything works perfectly. No trouble at all. But when I render the field into the template, and inspect it in my browser, I get the following:
<script>
window.testfield = '<select name="trigger" id="id_trigger">
<option value="a" selected>option a</option>
<option value="b">option b</option>
<option value="c">option c</option>
<option value="d">option d</option>
</select>'
</script>
This output breaks the html, and prevents the script tag from being interpreted as a variable like I want. This is a major problem, because I want to reuse these programmatically elsewhere on the page.
I tried the following:
<script>
window.testfield = '{{ form.testfield|escape }}'
</script>
But was still unsuccessful. Any help anyone can give would be greatly appreciated!
I am actively researching a solution. My current guess is that the output needs to be escaped somehow that I don't understand. I figure the template tags and filters have my answer, I just have to find it. Will post an update once a solution is found.
Use <script type="text/template"></script>.
This way the browser knows it's just text and will ignore it.
So, I figured it out. Turns out that the issue was that the presence of white space, line breaks, and unescaped double quotes (") were breaking the tag when it was parsed at HTML.
So I ended up using the following:
{% spaceless %}
<script>
window.testfield = '{{ form.testfield|addslashes }}'
</script>
{% endspaceless %}
And it worked, allowing me to store the string representation of the django form field in a javascript variable. As per the documentation, the {% spaceless %} "Removes whitespace between HTML tags. This includes tab characters and newlines." [1]. As for the filter |addslashes, it "Adds slashes before quotes. Useful for escaping strings in CSV" [2]. In my case, both solutions were needed, as without either of them, the script tag broke.
As for why the |escape filter didn't work on it's own, I'm not sure. Reading the documentation, it seems like it probably should have. The following is what the |escape filter actually does [3]:
Escapes a string’s HTML. Specifically, it makes these replacements:
< is converted to <
> is converted to >
' (single quote) is converted to '
" (double quote) is converted to "
& is converted to &
I can only guess why this didn't work. I figure it's because it didn't do anything about the white space. But I shouldn't speculate. I welcome any explanations you might have. As ever, understanding the way the machine thinks is better than any single, specific solution. Thanks.
[1] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless
[2] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#addslashes
[3] - https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escape

What is the proper syntax for using a django template variable as a jade href id reference?

I am trying to generate a navigation table using a django template for loop. The href target includes a django variable. The django template is written in jade format.
If i were using HTML format in the django template, I would use:
{{group.name}}
But I can't find the correct syntax using jade format.
What I have is:
table.generic
tbody
tr
th Jump to a Group
{% for group in groups %}
tr
td
a(href!='#{{group.name}}') {{group.name}}
{% endfor %}
But the anchors are rendered in HTML as:
<a +{group.name.__str__()+'}'="" href="">Registration</a>
"Registration" is a value for group.name.
Removing the ! causes a django render error.
I tried to insert a backslash: a(href!='#\{{group.name}}') {{group.name}}, but this renders with the backslash intact as:
Registration
Suggestions?
Edit: As a terrible work-around, I have added a "pound" method to return the group name with a # prefix:
def pound(self):
return unicode("#" + self.name)
Now I can reference {{group.pound}} in the jade template:
a(href!='{{group.pound}}') {{group.name}}
Maybe a better method name would be group.name_as_id_tag ....
RESOLVED: Format the django template variable as a jade variable
Based on the last suggestion from #user1737909, I extended the suggestion to try:
a(href='##{group.name}') {{group.name}}
The key is to format the double-curly django variable {{}} as pound-single-curly jade variable #{}. Do not include the ! before the = sign so the variable is evaluated by jade which will insert the value it gets from django.
I wish I could find a link to a coding style reference page to include here. But if I had one, I would not have asked this question in the first place.
Based on the last suggestion from #user1737909, I extended the suggestion to try:
a(href='##{group.name}') {{group.name}}
The key is to format the double-curly django variable {{}} as pound-single-curly jade variable #{}. Do not include the ! before the = sign so the variable is evaluated by jade which will insert the value it gets from django.
OP updated to reflect this solution.

Can I avoid this syntax highlighting confusion?

I have the following in my Django view:
<a title="{{ photo.time_taken|date:"N jS, 'y" }}" href='...' > {# ' #}
...
</a>
The problem is with wanting to format my date with the year as '13. The quotes get all confused, so I've had to put a django comment on the end to 'close' the quote, otherwise all following code is mis-highlighted. Is there a better way around this?
I'm using Sublime Text 2, with Djaneiro.