goe*_*elv 79 python django django-templates django-forms django-views
我想看看Django模板中的字段/变量是否为空.这个的正确语法是什么?
这就是我目前拥有的:
{% if profile.user.first_name is null %}
<p> -- </p>
{% elif %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我将用什么来代替"null"?
Ger*_*ard 108
None, False and True所有这些都在模板标签和过滤器中可用.None, False,空字符串('', "", """""")和空列表/元组都在评估False时评估if,因此您可以轻松完成
{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}
Run Code Online (Sandbox Code Playgroud)
提示:@fabiocerqueira是正确的,将逻辑留给模型,将模板限制为唯一的表示层,并在模型中计算类似的东西.一个例子:
# someapp/models.py
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
# other fields
def get_full_name(self):
if not self.user.first_name:
return
return ' '.join([self.user.first_name, self.user.last_name])
# template
{{ user.get_profile.get_full_name }}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助 :)
小智 46
您还可以使用其他内置模板 default_if_none
{{ profile.user.first_name|default_if_none:"--" }}
Run Code Online (Sandbox Code Playgroud)
小智 11
is运算符:Django 1.10 中的新功能
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
Run Code Online (Sandbox Code Playgroud)
Lou*_*uis 10
您还可以使用内置模板过滤器default:
如果值计算为 False(例如 None,空字符串,0,False);显示默认的“--”。
{{ profile.user.first_name|default:"--" }}
Run Code Online (Sandbox Code Playgroud)
文档:https : //docs.djangoproject.com/en/dev/ref/templates/builtins/#default
看看yesno助手
例如:
{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
Run Code Online (Sandbox Code Playgroud)