Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastapi : jinja2.exceptions.TemplateNotFound: index.html

I am trying with the below code to redirect to login page using fastapi. I used TemplateResponse to redirect to index.html page which I already created inside the templates folder.

File structure as follows

- main.py
- templates -> index.html
- static

main.py

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
async def login_page(request :Request):
    return templates.TemplateResponse("index.html", {"request":request})

I tried doing it but I am getting an error "jinja2.exceptions.TemplateNotFound: index.html" and when I insert some HTML code statically it's working but TemplateResponse is not working properly. Even when I tried giving an entire path of the HTML file inside the templates folder it's giving a different error.

Please guide me on how to make this code work as I tried with different ways but in any case, this code is giving an error index.html template not found

like image 860
Sagabarnisa S Avatar asked Apr 07 '26 08:04

Sagabarnisa S


1 Answers

I just had the same problem when I was doing unit testing and solved it as follows:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent

templates = Jinja2Templates(directory=str(Path(BASE_DIR, 'templates')))
like image 193
Julin Fernando Sandoval Vargas Avatar answered Apr 08 '26 21:04

Julin Fernando Sandoval Vargas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!