Jinja2 returns “None” string for Google App Engine

2019-05-24 22:52发布

Google App Engine models, likeso:

from google.appengine.ext.db import Model

class M(Model):
    name = db.StringProperty()

Then in a Jinja2 template called from a Django view with an in instance of M passed in as m:

The name of this M is {{ m.name }}.

When m is initialized without name being set, the following is printed:

The name of this M is None.

The preferable and expected output (and the output when using Django templates) would be/is:

The name of this M is .

Do you know why this is happening, and how to get the preferred & expected output?

3条回答
Evening l夕情丶
2楼-- · 2019-05-24 23:27

What if he doesn't want empty string to be the default value?

I have this issue myself. I don't want empty string in there. I want null/None/NoneType. That's not the same as empty string.

So I put the question to everyone again --- Jinja insists on translating "None". What gives?

查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-24 23:40

You might also want to consider using Jinja2's "or"...

The name of this M is {{ m.name or ''}}.

If bool(m.name) == False, this will show The name of this M is .


If m.name == False and you want to display it as the string "False", you can use Jinja2's "default" filter:

The name of this M is {{ m.name|default('') }}

If m.name is None, this will show The name of this M is .

If m.name == False, this will show The name of this M is False.


If you want to use the default filter and still have anything evaluating to False shown as your defined default value, add an extra param:

The name of this M is {{ m.name|default('', true) }}

This should have the exact same effect as {{ m.name or '' }}.


You can find all of this information on Jinja2's Builtin Filters reference

查看更多
SAY GOODBYE
4楼-- · 2019-05-24 23:42

I think you hit upon the answer yourself. If you don't specify a name for that property, App Engine appears to store it as None, not "", so when it's printed, it gets printed as "None". Specify the default as "" and your problem goes away, like you said.

查看更多
登录 后发表回答