I am able to get else part of the code, Else part is not working

91 Views Asked by At

I am working on this code of logging in to the application. I can see that only if statement is working in this code for the valid values of username and password. If i enter the invalid values of username and password the else part should work, But it's not working.

**main.py**

@app.post("/loginsuccess/", response_class=HTMLResponse)
async def login_success(request: Request, username: str = Form(...), password: str = Form(...)):
    p = await User_Pydantic.from_tortoise_orm(await User.get(username=username, password=password))
    json_compatible_item_data = jsonable_encoder(p)
    if json_compatible_item_data['username']==username and json_compatible_item_data['password']==password:
        
        print(json_compatible_item_data["username"], "22222222222222222")
        return templates.TemplateResponse("homepage.html", {"request": request, "username":username})
    else:
        print("NOOOOOOOOOOOOOOOOO")
        status_code:int
        status_code = 500
        return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code})
    
2

There are 2 best solutions below

8
On

from_tortoise_orm returns a pydantic object which is never None because an instance of a class is always a non-None object(unless you override the __eq__ behaviour in the class definition).

Instead of comparing the the object p, you can try comparing jsonable_encoder(p):

json_compatible_item_data = jsonable_encoder(p)
if json_compatible_item_data:
    print(json_compatible_item_data["username"], "22222222222222222")
    ...
else:
    print("NOOOOOOOOOOOOOOOOO")
    ...

Update(based on OP's comment)

You can do

if not json_compatible_item_data.get('detail') == 'Object does not exist':
    ...
else:
    print("NOOOOOOOOOOOOOOOOO")
    ...
0
On

I'm not a expert of Django or Flask, but I think using is not is making it not work use != None