Jinja2 returns “None” string for Google App Engine models

吃可爱长大的小学妹 提交于 2019-12-22 18:27:28

问题


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?


回答1:


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




回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/2695180/jinja2-returns-none-string-for-google-app-engine-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!