pythonflask

Error in Machine Learning Flask App - jinja2.exceptions.TemplateNotFound: index.html


I am doing a Machine Learning Flask project on Electric Vehicle Price Prediction. I have been stuck on an issue for 2 days.

After running python run.py command, I get this error at localhost:

TemplateNotFound
jinja2.exceptions.TemplateNotFound: index.html

Traceback (most recent call last)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 1498, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 1476, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 1473, in wsgi_app
response = self.full_dispatch_request()Open an interactive python shell in this frame
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 882, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 880, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\app.py", line 865, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)  # type: ignore[no-any-return]
File "G:\Machine_Learning_Projects\2024\electric_vehicle_price_prediction_2\app\routes.py", line 7, in index
return render_template('index.html')
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\templating.py", line 149, in render_template
template = app.jinja_env.get_or_select_template(template_name_or_list)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\environment.py", line 1084, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\environment.py", line 1013, in get_template
return self._load_template(name, globals)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\environment.py", line 972, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\jinja2\loaders.py", line 126, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\templating.py", line 65, in get_source
return self._get_source_fast(environment, template)
File "C:\Users\2021\.conda\envs\electric_vehicle_price_prediction_2\lib\site-packages\flask\templating.py", line 99, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: index.html
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

Here is my code in routes.py file inside app folder:

from flask import render_template, request, jsonify
from app import app
from app.model import predict_price

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    data = request.form.to_dict()
    
    # Convert the form data into the correct format for prediction
    features = [
        data['county'],
        data['city'],
        data['zip_code'],
        data['model_year'],
        data['make'],
        data['model'],
        data['ev_type'],
        data['cafv_eligibility'],
        data['legislative_district']
    ]
    
    # Get the prediction result
    price = predict_price(features)
    
    return jsonify({'predicted_price': price}

)

Here is my code in index.html file inside template folder:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EV Price Prediction</title>
</head>
<body>
    <h1>Electric Vehicle Price Prediction</h1>
    
    <form action="/predict" method="POST">
        <label for="county">County:</label>
        <input type="text" id="county" name="county"><br><br>

        <label for="city">City:</label>
        <input type="text" id="city" name="city"><br><br>

        <label for="zip_code">ZIP Code:</label>
        <input type="text" id="zip_code" name="zip_code"><br><br>

        <label for="model_year">Model Year:</label>
        <input type="text" id="model_year" name="model_year"><br><br>

        <label for="make">Make:</label>
        <input type="text" id="make" name="make"><br><br>

        <label for="model">Model:</label>
        <input type="text" id="model" name="model"><br><br>

        <label for="ev_type">Electric Vehicle Type:</label>
        <input type="text" id="ev_type" name="ev_type"><br><br>

        <label for="cafv_eligibility">CAFV Eligibility:</label>
        <input type="text" id="cafv_eligibility" name="cafv_eligibility"><br><br>

        <label for="legislative_district">Legislative District:</label>
        <input type="text" id="legislative_district" name="legislative_district"><br><br>

        <input type="submit" value="Predict">
    </form>
    
    <div id="result">
        {% if predicted_price %}
            <h2>Predicted Price: ${{ predicted_price }}</h2>
        {% endif %}
    </div>
</body>
</html>

Here is my GitHub repo:

https://github.com/MdEhsanulHaqueKanan/electric-vehicle-price-prediction-2

Looking at other similar questions online, I thought that I might have a problem with my project folder structure. But I have double checked my folder structure. I haven't found any issue with it.

You can see my project folder structure here:

ev_price_prediction/
│
├── app/
│   ├── __init__.py
│   ├── routes.py
│   └── model.py
│
├── static/
│   └── style.css
│
├── templates/
│   └── index.html
│
├── dataset/
│   └── train.csv
│   └── test.csv
│
├── requirements.txt
└── run.py

Would you please help me to fix this isssue?


Solution

  • As mentioned in the official document :

    Jinja uses a central object called the template Environment. Instances of this class are used to store the configuration and global objects, and are used to load templates from the file system or other locations
    

    So you will need to create a template environment first, like:

    env = Environment(
        loader=PackageLoader("app"),
        autoescape=select_autoescape()
    )
    

    And then move the template directory under your app directory:

     ev_price_prediction/
    │
    ├── app/
    │   ├── __init__.py
    │   ├── routes.py
    │   ├── model.py
    │   └── templates/
    │       └── index.html 
    │
    ├── static/
    │   └── style.css
    │
    │
    ├── dataset/
    │   └── train.csv
    │   └── test.csv
    │
    ├── requirements.txt
    └── run.py
    

    Then you can load template from the template environment:

    @app.route('/')
    def index():
        env = Environment(
            loader=PackageLoader("app"),
            autoescape=select_autoescape()
        )
        template = env.get_template("index.html")
        return render_template(template)