[Answer]-If statement in django

0👍

You are not looping in the first code block as the return isn’t indented correctly.

for name in tree.iter('name'):
    if name.text.lower() == nome.lower():
        c = Context({'id' : name.text})
        r1 = HttpResponse(t.render(c), mimetype='application/xml')
        return r1
 # move return indentation to match here, i.e after the for loop completes

See how the return is matched in your second block when using else

for name in tree.iter('name'):
    if name.text.lower() == nome.lower():
        c = Context({'id' : name.text})
        r1 = HttpResponse(t.render(c), mimetype='application/xml')
    else:  r1 = HttpResponse(t.render(Context({'id' : 'prova'})), mimetype='application/xml')
return r1

1👍

You are looping over multiple elements in the tree. In your first version you are returning immediately when processing the first element. In the second version you only return after processing all elements in the tree.

Either return from within the loop or determine what needs to be done with the multiple matches:

for name in tree.iter('name'):
    if name.text.lower() == nome.lower():
        c = Context({'id' : name.text})
        r1 = HttpResponse(t.render(c), mimetype='application/xml')
    else:  r1 = HttpResponse(t.render(Context({'id' : 'prova'})), mimetype='application/xml')
    return r1  # return the *first* match.

Leave a comment