# Set up sidebar
with st.sidebar:
    st.title("Add New Product")
    product_url = st.text_input("Product URL")
    add_button = st.button("Add Product")

    if add_button:
        if not product_url:
            st.error("Please enter a product URL")
        elif not is_valid_url(product_url):
            st.error("Please enter a valid URL")
        else:
            db.add_product(product_url)  # This is the new line
            st.success("Product is now being tracked!")

```

In the final `else` block that runs when the product URL is valid, we call the `add_product` method to store the product in the database.

Let’s commit everything:

```bash
git add .
git commit -m "Add a Postgres database integration for tracking product URLs"

```

### Step 6: Storing price histories for new products

Now, after the product is added to the `products` table, we want to add its details and its scraped price to the `price_histories` table.

First, switch to `database.py` and add a new method for creating entries in the `PriceHistories` table:

```python
class Database:
    ...  # the rest of the class

    def add_price(self, product_data):
        session = self.Session()
        try:
            price_history = PriceHistory(
                id=f"{product_data['url']}_{product_data['timestamp']}",
                product_url=product_data["url"],
                name=product_data["name"],
                price=product_data["price"],
                currency=product_data["currency"],
                main_image_url=product_data["main_image_url"],
                timestamp=product_data["timestamp"],
            )
            session.add(price_history)
            session.commit()
        finally:
            session.close()

```

The `add_price` method takes a dictionary containing product data (which is returned by our scraper) and creates a new entry in the `PriceHistory` table. The entry’s ID is generated by combining the product URL with a timestamp. The method stores essential product information like name, price, currency, image URL, and the timestamp of when the price was recorded. It uses SQLAlchemy’s session management to safely commit the new price history entry to the database.

Now, we need to add this functionality to the sidebar as well. In `ui.py`, add a new import statement that loads the `scrape_product` function from `scraper.py`:

```python
...  # The rest of the imports
from scraper import scrape_product

```

Then, update the `else` block in the sidebar again:

```python
with st.sidebar:
    st.title("Add New Product")
    product_url = st.text_input("Product URL")
    add_button = st.button("Add Product")

    if add_button:
        if not product_url:
            st.error("Please enter a product URL")
        elif not is_valid_url(product_url):
            st.error("Please enter a valid URL")
        else:
            db.add_product(product_url)
            with st.spinner("Added product to database. Scraping product data..."):
                product_data = scrape_product(product_url)
                db.add_price(product_data)
            st.success("Product is now being tracked!")

```

Now when a user enters a product URL and clicks the “Add Product” button, several things happen:

1. The URL is validated to ensure it’s not empty and is properly formatted.
2. If valid, the URL is added to the products table via `add_product()`.
3. The product page is scraped immediately to get current price data.
4. This initial price data is stored in the price history table via `add_price()`.
5. The user sees loading spinners and success messages throughout the process.

This gives us a complete workflow for adding new products to track, including capturing their initial price point. The UI provides clear feedback at each step and handles errors gracefully.

Check that everything is working the way we want it and then, commit the new changes:

```bash
git add .
git commit -m "Add a feature to track product prices after they are added"

```

### Step 7: Displaying each product’s price history in the main dashboard

Let’s take a look at the final product shown in the introduction once again:

![Screenshot of a minimalist price tracking dashboard showing product price history charts, add/remove product controls, and notification settings for monitoring e-commerce deals and price drops](https://www.firecrawl.dev/images/blog/price-tracking/sneak-peek.png)

Apart from the sidebar, the main dashboard shows each product’s price history visualized with a Plotly line plot where the X axis is the timestamp while the Y axis is the prices. Each line plot is wrapped in a Streamlit component that includes buttons for removing the product from the database or visiting its source URL.

In this step, we will implement the plotting feature and leave the two buttons for a later section. First, add a new method to the `Database` class for retrieving the price history for each product:

```python
class Database:
    ...  # The rest of the code

    def get_price_history(self, url):
        """Get price history for a product"""
        session = self.Session()
        try:
            return (
                session.query(PriceHistory)
                .filter(PriceHistory.product_url == url)
                .order_by(PriceHistory.timestamp.desc())
                .all()
            )
        finally:
            session.close()

```

The method queries the price histories table based on product URL, orders the rows in descending order (oldest first) and returns the results.

Then, add another method for retrieving all products from the `products` table:

```python
class Database:
    ...

    def get_all_products(self):
        session = self.Session()
        try:
            return session.query(Product).all()
        finally:
            session.close()

```

The idea is that every time our Streamlit app is opened, the main dashboard queries all existing products from the database and render their price histories with line charts in dedicated components.

To create the line charts, we need Plotly and Pandas, so install them in your environment:

```bash
pip install pandas plotly
echo "pandas\nplotly\n" >> requirements.txt

```

Afterward, import them at the top of `ui.py` along with other existing imports:

```python
import pandas as pd
import plotly.express as px

```

Then, switch to `ui.py` and paste the following snippet of code after the Main content section:

```python