質問

戻る方法を探しています True または文字列で、後でその情報を使用して何かを表示します。これが私のコードです:

def time_remaining(self):
    timer = self.timer
    now = datetime.datetime.utcnow().replace(tzinfo=utc)
    if timer < now:
        return True
    else:
        #Returns a timedelta in string
        return game_logic.timedelta_format(timer - now)

その後、私は使用します:

if time_remaining():
    possible = True
else:
    possible = False

return render(request, 'training.html',{'possible': possible})

そして最後に私のテンプレートで:

{% if possible %}
    <some html>
{% else %}
    <different html>
{% endif %}

どういうわけか、私は常にtime_remainingがtrueの代わりに文字列を返している場合でも終わります

この問題を修正するにはどうすればよいですか?

役に立ちましたか?

解決

Pythonでは、空でない文字列もAsを評価します True:

>>> bool('foo')
True
>>> bool('')
False

何があっても time_remaining 関数が戻り、常にとして評価されます True あなたの中で if 声明。

あなたはおそらく次のようなものを使いたいです:

time_remaining() == True

または、おそらく持っています time_remaining 戻る False また None 時間がない場合(特にあなたがの出力のみを使用する場合の場合 time_remaining あなたの中で if 声明)。

他のヒント

time_remaining() == True:

それはトリックをしているようです:)それは常に何かを返していると考えました。

君の time_remaining 関数は常に評価する値を返します True の中に if 声明。そう possible 常になります True.

Time Deltaの値をテストするなど、2番目のコードブロックにいくつかの追加ロジックを追加して、期待する動作を実行します。

関数出力は同じタイプである必要があり、空の出力を指示するための特別な値「なし」があります(ただし、このステートメントの参照は見つかりません...)。

だから、あなたはするべきです:

if timer < now:
    return game_logic.timedelta_format(empty_timedelta) 
else:
    #Returns a timedelta in string
    return game_logic.timedelta_format(timer - now)

また:

time_limit = min(timer, now) #if 'min' applies
return game_logic.timedelta_format(timer - time_limit ) 

また:

if timer < now:
    return None
else:
    #Returns a timedelta in string
    return game_logic.timedelta_format(timer - now)

またはいくつかの値を返します:最初の値は結果の種類を伝えます、2番目は実際の結果です

if timer < now:
    return (True, None)
else:
    #Returns a timedelta in string
    return (False, game_logic.timedelta_format(timer - now))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top