Return message from Else

Asked

Viewed 60 times

2

I’m making a very simple example using Django.

In my view I have the following :

def index(request,idade):

    string = '''
        {% if idoso >= 65 %}
            Você já é idoso
        {% else %}
            Você não é idoso
        {% endif %}
    '''
    t = template.Template(string)
    c = template.Context({'idoso':idade})
    return HttpResponse(t.render(c))

But even if I pass any value it will always return the if message, IE, if I pass 10 it will return: you are old.

Does anyone know why this is happening ?

Note: Usage Django 1.11.

  • Beto , check if you are actually passing some value to your view, if can be accessed because it is passing the wrong value. You have the predecessor code of this ? where you define the values ? ?

  • Otávio Reis Perkles, was the type of variable that was not in the correct form to pass to Context. I was doing it this way only as a way of learning, but it’s really better to use it in html.

1 answer

1

Probably doing something like:

 url(r'^algo/(?P<idade>\d+)/$', views.index)

When passing the value by a regex it may not be in the desired type even if you use the \d+, for example.

To solve this problem it is best to make sure that it will be in the desired type, so do :

int(idade) 

That way the code below works well.

def index(request,idade):

string = '''
    {% if idoso >= 65 %}
        Você já é idoso
    {% else %}
        Você não é idoso
    {% endif %}
'''
t = template.Template(string)
c = template.Context({'idoso':int(idade)})
return HttpResponse(t.render(c))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.