Creating strings with jinja structure inside - python

I'm trying to generate django code, however when trying to create the templates,
classname = 'person'
content = "{% trans 'Add' %}\n" % classname
I get the following error:
TypeError: %u format: a number is required, not unicode
Python tries to evaluate the "{% u" and I get that error.
I tried also with "format" but error stays.

You can double encode jinja's % characters:
content = "{%% trans 'Add' %%}\n" % classname
or double encode Jinjas {} characters and use format():
content = "{{% trans 'Add' %}}\n".format(classname=classname)
Or simply split your template into three parts:
content = "<a href='{% url 'core.views.add_"
content += '%s' % classname
cotnent += " %}' class=\"btn btn-default\">{% trans 'Add' %}</a>\n"

You can do simple string concatenation in this case:
content = "{% trans 'Add' %}\n"
Example:
>>> classname = 'person'
>>> content = "{% trans 'Add' %}\n"
>>> content
>>> '{% trans \'Add\' %}\n'

If you want a literal % in your string, use two percent signs %%:
"{%% trans 'Add' %%}\n" % classname
If you use the format() method, you need to use {{ and }}:
"{{% trans 'Add' %}}\n".format(classname)

Related

How do you pass an array to a mako template?

I want to pass an array of strings to Mako's render method but this doesn't work:
from mako.template import Template
mytemplate = Template(filename="some.template")
str = mytemplate.render(first="John", last="Smith", nicknames=[
"JJ", "Johnny", "Jon"])
print(str)
some.template =
Hello ${first} ${last}
Your nicknames are:
% for n in ${nicknames}:
${n}
% endfor
Within a '%' line, you're writing regular Python code that doesn't need the escaping:
% for n in nicknames:
${n}
% endfor

How to get USER input from html and search for it in databse with Python

I have a database and i want to search in it with this HTML
<form action="/question/search" method="POST">
<input id="search" type="text" placeholder="Search.." name="search">
<button id="search" type="submit">🔍</button>
</form>
I get the data in my function
#app.route("/question/search",methods=["POST"])
def search():
search_result = request.form.get("search")
story = data_handler.get_search_result(search_result)
return render_template('search_resoult.html', stories=story)
but i just cant figure out the SQl for it i tried :
#database_common.connection_handler
def get_search_result(cursor,item):
my_sql = "SELECT * FROM question WHERE title LIKE %s OR message LIKE %s"
my_resoult = (item)
cursor.execute(my_sql, my_resoult)
resoult = cursor.fetchall()
return resoult
I just want to all the data that has my_result in the title or in the message.
It always gives me this error:
TypeError: not all arguments converted during string formatting
The problem is that your query requires 2 values to be unpacked, but you're only giving a single one (item). If you want to use item as the condition for both title LIKE and message LIKE, you should expand my_resoult:
my_resoult = (item, item)

What's the most Pythonic/Django-y way to store long string assets?

I have a function in my Django app that has a dictionary containing several long strings. When that function is called, those strings are formatted and the dictionary returned.
For example:
def my_strings(foo, bar, baz):
return = {
'string1': 'a really long string! %s' % foo,
'string2': 'another long one. %s %s' % (foo, bar),
'string3': 'yet another! %s %s %s' % (foo, bar, baz),
}
However, having all these long strings, stored in a Python file is ugly and it seems there should be a cleaner way to do it.
I'd toyed with putting them in a template file and doing some rendering, like so:
mytemplate.txt
{% if string1 %}
a really long string! {{ foo }}
{% endif %}
{% if string2 %}
another long one. {{ foo }} {{ bar }}
{% endif %}
{% if string3 %}
yet another! {{ foo }} {{ bar }} {{ baz }}
{% endif %}
Python
def my_strings(foo, bar, baz):
arg_dict = {
'foo': foo,
'bar': bar,
'baz': baz,
}
my_strings = {}
string_names = ['string1', 'string2', 'string3']
for s in string_names:
arg_dict[s] = True
my_strings[s] = render_to_string('mytemplate.txt', arg_dict).strip()
del arg_dict[s]
return my_strings
But that seems a little too roundabout, and most likely less performant.
Is there a preferred way in Python, or Django specifically, to handle storing and formatting long string assets?
Some extra context: the string assets are either HTML or plaintext. The dictionary is eventually iterated over and all instances of each key in yet another string are replaced with its string value.
I would treat this as something similar to the way many i8n compilation code does it.
Store the long strings in a dictionary in a separate file. Import that dictionary and then format the desired string in your code.
You could place the strings in a module like longstrings.py
STRING1 = ("Bla bla"
" more text"
" even more text")
STRING2 = ("Bla bla"
" more text"
" even more text")
and then
from longstrings import *
def my_strings(foo, bar, baz):
return = {
'string1': STRING1 % foo,
'string2': STRING2 % (foo, bar),
'string3': STRING2 % (foo, bar, baz),
}
You could also create a class for your long strings, and they would be stored in the DB. This would allow you to access them and modify them as any other object. For example, you could use the Django admin tool if you want to modify a specific string.

Get data from sqllite and display it on html page in Django

I'am trying to display data from the database file which has the value Age : 50 but
i alway get "Age object" displayed in the html. I'm very new too Django.
Here is the code
//base.HTML displays :
Age object
//base.html code :
<body>
{{ obj }}
</body>
//views.py :
def home(request):
obj = Age.objects.all()
return render_to_response("base.html",{'obj': obj})
//models.py
class Age(models.Model):
age = models.CharField(max_length=100)
simply obj is an array of objects, you have to print the attribute of the object.
If you want to show only one age(the first) you have to do:
//views.py :
def home(request):
obj = Age.objects.all()[0]
return render_to_response("base.html",{'obj': obj})
//base.html code :
<body>
{{ obj.age }}
</body>
You need to specify what field to show.
{{ obj.age }}
You need to either do obj.age in the template, or implement str or unicode method on your object that returns the age.

How to display string which contains django template variables?

Let's say I have an string variable called *magic_string* which value is set to "This product name is {{ product.name }}" and it's avaible at django template. Is it ever possible to parse that variable to show me "This product name is Samsung GT-8500" instead (assuming that name of the product is "GT-8500" and variable {{ product.name }} is avaible at the same template) ?
I was trying to do something like this, but it doesn't work (honestly ? Im not surprised):
{{ magic_string|safe }}
Any ideas/suggestions about my problem ?
Write custom template tag and render that variable as a template.
For example look at how "ssi" tag is written.
On the other hand, can you render this string in your view? Anyway here is an untested version of that tag:
#register.tag
def render_string(parser, token):
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError("...")
return RenderStringNode(bits[1])
class RenderStringNode(Node):
def __init__(self, varname):
self.varname = varname
def render(self, context):
var = context.get(self.varname, "")
return Template(var).render(context)
Perhaps I dont understand your question but what about,
from django.template import Context, Template
>>> t = Template("This product name is {{ product.name }}")
>>> c = Context({"product.name": " Samsung GT-8500"})
>>> t.render(c)
Regards.

Categories

Resources