'<' not supported between instances of 'NoneType' and 'int' django views.py

templates/html

            {% if guess == rand_num %}
            <h1>{{message1}}</h1>
            {% elif guess > rand_num %}
            <h1>{{message3_a}}</h1>
            <h1>{{message3_b}}</h1>
            {% elif guess < rand_num %}
            <h1>{{message2_a}}</h1>
            <h1>{{message2_b}}</h1>
            {% endif %}

views.py

def easy(request, ): rand_num = random.choice(lst) print(rand_num) attempts = 11 for _ in range(0, 10): # print(f"You have {attempts} remaining to guess the number.") # guess = int(input("Make a guess: ")) guess = request.GET.get('guessed_number') if guess == rand_num: return render(request, 'easy.html', {'attempts': attempts, "message1": f"You got it! The anshwer was {rand_num}"})
break elif guess < rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message2_a": "Too Low", "message2_b": "Guess again"})
elif guess > rand_num: attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, "message3_a": "Too High", "message2_b": "Guess again"})
attempts -= 1 return render(request, 'easy.html', {'attempts': attempts, 'guess': guess, 'rand_num': rand_num}) return render(request, 'easy.html')

i Am triying to Run this Django code. but it is not running..

You can explicitly check if the variables exist before performing the comparison.

{% if guess is not None and rand_num is not None %}
    {% if guess == rand_num %}
        <h1>{{ message1 }}</h1>
    {% elif guess > rand_num %}
        <h1>{{ message3_a }}</h1>
        <h1>{{ message3_b }}</h1>
    {% elif guess < rand_num %}
        <h1>{{ message2_a }}</h1>
        <h1>{{ message2_b }}</h1>
    {% endif %}
{% else %}
    <h1>No guess or random number provided.</h1>
{% endif %}

Alternatively, You can use the default filter to provide a default value if the variable is not present or is None

{% if guess is not None or rand_num is not None %}
    {% if guess|default:0 == rand_num|default:0 %}
        <h1>{{ message1 }}</h1>
    {% elif guess|default:0 > rand_num|default:0 %}
        <h1>{{ message3_a }}</h1>
        <h1>{{ message3_b }}</h1>
    {% elif guess|default:0 < rand_num|default:0 %}
        <h1>{{ message2_a }}</h1>
        <h1>{{ message2_b }}</h1>
    {% endif %}
{% else %}
    <h1>No guess or random number provided.</h1>
{% endif %}
Вернуться на верх