Django テンプレート内のフィールド/変数が none かどうかを確認したいです。そのための正しい構文は何ですか?
現在私が持っているものは次のとおりです:
{% if profile.user.first_name is null %}
<p> -- </p>
{% elif %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}
上記の例では、「null」を置き換えるには何を使用すればよいでしょうか?
ベストアンサー1
None, False and True
これらはすべてテンプレートタグとフィルタ内で利用可能です。None, False
、空文字列('', "", """"""
)と空のリスト/タプルはすべてFalse
で評価されるのでif
、簡単に次のようにすることができます。
{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}
ヒント: @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 }}