Djangoテンプレート内にフィールド/変数がないかどうかを確認したいと思います。そのための正しい構文は何ですか?
これは私が現在持っているものです:
{% if profile.user.first_name is null %}
<p> -- </p>
{% elif %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}
上記の例では、「null」を置き換えるために何を使用しますか?
Djangoテンプレート内にフィールド/変数がないかどうかを確認したいと思います。そのための正しい構文は何ですか?
これは私が現在持っているものです:
{% if profile.user.first_name is null %}
<p> -- </p>
{% elif %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}
上記の例では、「null」を置き換えるために何を使用しますか?
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 }}
お役に立てれば :)
別の組み込みテンプレートを使用することもできますdefault_if_none
{{ profile.user.first_name|default_if_none:"--" }}
組み込みのテンプレート フィルターを使用することもできますdefault。
値が False と評価された場合 (たとえば、None、空の文字列、0、False)。デフォルトの「--」が表示されます。
{{ profile.user.first_name|default:"--" }}
ドキュメント: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default
isoperator : Django 1.10 の新機能
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
{% if profile.user.first_name %}動作します(あなたも受け入れたくないと仮定します'')。
ifPythonでは、一般に、、、、、、None...Falseを''すべて[]false{}として扱います。