I'v written this code in this way:

import streamlit as st
from src.utils.db import DataBaseManager
import base64
import random
import string


# if 'edit_template_flag' not in st.session_state:
#     st.session_state['edit_template_flag'] = False


def main():
    st.title("Email Templates 📝")
    st.write("Create and manage your email templates.")

    db_manager = DataBaseManager()

    # Form to add a new template
    st.subheader("Add a New Template")
    with st.form("template_form", clear_on_submit=True):
        title = st.text_input("Template Title")
        subject = st.text_input("Subject")
        body = st.text_area("Body")
        submitted = st.form_submit_button("Add Template")

        if submitted:
            if not title or not subject or not body:
                st.warning("Please fill in all fields.")
            else:
                template_data = {
                    'title': title,
                    'subject': subject,
                    'body': body
                }
                db_manager.add_template(template_data)
                st.success(f"Template '{title}' added successfully!")
                # st.rerun()  # Rerun to update the list after addition

    # Display existing templates
    st.subheader("Existing Templates")
    templates = db_manager.list_templates()
    if templates:
        # Search Functionality
        search_query = st.text_input("Search Templates")
        if search_query:
            templates = [t for t in templates if search_query.lower() in t['title'].lower() or search_query.lower() in t['subject'].lower()]
            if not templates:
                st.info("No templates match your search.")
                return

        # Organize templates in columns
        cols = st.columns(2)  # Adjust the number of columns as needed
        for idx, template in enumerate(templates):
            col = cols[idx % 2]
            with col:
                display_template(db_manager, template)

    else:
        st.info("No templates have been added.")

def display_template(db_manager, template):
    st.markdown(f"### {template['title']}")
    st.markdown(f"Subject: {template['subject']}")
    st.markdown("Body:")
    st.code(template['body'], language='markdown')  # Display body in a code block
    action_col1, action_col2, action_col3 = st.columns([1,1,2])
    with action_col1:
        if st.button('✏️ Edit', key=f"edit_{template['title']}"):
            st.session_state.edit_template_flag = True
            st.write(st.session_state.edit_template_flag)
    if 'edit_template_flag' in st.session_state:
        edit_template(db_manager, template)
        st.write(st.session_state.edit_template_flag)
        del st.session_state['edit_template_flag']
        st.write('editted')
    with action_col2:
        if st.button('❌ Delete', key=f"delete_{template['title']}"):
            db_manager.delete_template(template.doc_id)
            st.success(f"Template '{template['title']}' deleted successfully!")
            st.rerun()
    with action_col3:
        clipboard_button(template['body'], "📋 Copy Body")

def edit_template(db_manager, template):
    st.subheader(f"Edit Template: {template['title']}")
    st.write('template.doc_id', template.doc_id)
    with st.form(f"edit_form_{template['title']}"):
        title = st.text_input("Template Title", value=template['title'])
        subject = st.text_input("Subject", value=template['subject'])
        body = st.text_area("Body", value=template['body'])
        submitted = st.form_submit_button("Save Changes")

        if submitted:
            # st.write('submitted')
            if not title or not subject or not body:
                st.warning("Please fill in all fields.")
            else:
                updated_template = {
                    'title': title,
                    'subject': subject,
                    'body': body
                }
                # st.write(updated_template)
                db_manager.update_template(template.doc_id, updated_template)
                # del st.session_state['edit_template_flag']

                # st.write(db_manager.list_templates())
                st.success(f"Template '{template['title']}' updated successfully!")
                st.rerun()

def clipboard_button(text, button_text="Copy to Clipboard"):
    import streamlit.components.v1 as components
    button_id = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
    custom_css = f"""
    <style>
    #{button_id} {{
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f0f0;
        color: #000;
        border: none;
        padding: 4px 8px;
        margin-top: 5px;
        cursor: pointer;
        border-radius: 4px;
        font-size: 14px;
    }}
    #{button_id}:hover {{
        background-color: #e0e0e0;
    }}
    </style>
    """
    copy_code = f"""
    <button id="{button_id}">{button_text}</button>
    <script>
    const el = document.getElementById("{button_id}");
    el.addEventListener("click", function() {{
        navigator.clipboard.writeText({text});
        el.textContent = 'Copied!';
        setTimeout(() => el.textContent = '{button_text}', 2000);
    }});
    </script>
    """
    components.html(f"{custom_css}{copy_code}", height=45)


if __name__ == "__main__":
    main()


but it is not working. it is not update template.
it seems where we put 'del st.session_state['edit_template_flag']'  is so important, because when I modify to this:

import streamlit as st
from src.utils.db import DataBaseManager
import base64
import random
import string


# if 'edit_template_flag' not in st.session_state:
#     st.session_state['edit_template_flag'] = False


def main():
    st.title("Email Templates 📝")
    st.write("Create and manage your email templates.")

    db_manager = DataBaseManager()

    # Form to add a new template
    st.subheader("Add a New Template")
    with st.form("template_form", clear_on_submit=True):
        title = st.text_input("Template Title")
        subject = st.text_input("Subject")
        body = st.text_area("Body")
        submitted = st.form_submit_button("Add Template")

        if submitted:
            if not title or not subject or not body:
                st.warning("Please fill in all fields.")
            else:
                template_data = {
                    'title': title,
                    'subject': subject,
                    'body': body
                }
                db_manager.add_template(template_data)
                st.success(f"Template '{title}' added successfully!")
                # st.rerun()  # Rerun to update the list after addition

    # Display existing templates
    st.subheader("Existing Templates")
    templates = db_manager.list_templates()
    if templates:
        # Search Functionality
        search_query = st.text_input("Search Templates")
        if search_query:
            templates = [t for t in templates if search_query.lower() in t['title'].lower() or search_query.lower() in t['subject'].lower()]
            if not templates:
                st.info("No templates match your search.")
                return

        # Organize templates in columns
        cols = st.columns(2)  # Adjust the number of columns as needed
        for idx, template in enumerate(templates):
            col = cols[idx % 2]
            with col:
                display_template(db_manager, template)

    else:
        st.info("No templates have been added.")

def display_template(db_manager, template):
    st.markdown(f"### {template['title']}")
    st.markdown(f"Subject: {template['subject']}")
    st.markdown("Body:")
    st.code(template['body'], language='markdown')  # Display body in a code block
    action_col1, action_col2, action_col3 = st.columns([1,1,2])
    with action_col1:
        if st.button('✏️ Edit', key=f"edit_{template['title']}"):
            st.session_state.edit_template_flag = True
            st.write(st.session_state.edit_template_flag)
    if 'edit_template_flag' in st.session_state:
        edit_template(db_manager, template)
        st.write(st.session_state.edit_template_flag)
        # del st.session_state['edit_template_flag']
        st.write('editted')
    with action_col2:
        if st.button('❌ Delete', key=f"delete_{template['title']}"):
            db_manager.delete_template(template.doc_id)
            st.success(f"Template '{template['title']}' deleted successfully!")
            st.rerun()
    with action_col3:
        clipboard_button(template['body'], "📋 Copy Body")

def edit_template(db_manager, template):
    st.subheader(f"Edit Template: {template['title']}")
    st.write('template.doc_id', template.doc_id)
    with st.form(f"edit_form_{template['title']}"):
        title = st.text_input("Template Title", value=template['title'])
        subject = st.text_input("Subject", value=template['subject'])
        body = st.text_area("Body", value=template['body'])
        submitted = st.form_submit_button("Save Changes")

        if submitted:
            # st.write('submitted')
            if not title or not subject or not body:
                st.warning("Please fill in all fields.")
            else:
                updated_template = {
                    'title': title,
                    'subject': subject,
                    'body': body
                }
                # st.write(updated_template)
                db_manager.update_template(template.doc_id, updated_template)
                del st.session_state['edit_template_flag']

                # st.write(db_manager.list_templates())
                st.success(f"Template '{template['title']}' updated successfully!")
                st.rerun()

def clipboard_button(text, button_text="Copy to Clipboard"):
    import streamlit.components.v1 as components
    button_id = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
    custom_css = f"""
    <style>
    #{button_id} {{
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f0f0;
        color: #000;
        border: none;
        padding: 4px 8px;
        margin-top: 5px;
        cursor: pointer;
        border-radius: 4px;
        font-size: 14px;
    }}
    #{button_id}:hover {{
        background-color: #e0e0e0;
    }}
    </style>
    """
    copy_code = f"""
    <button id="{button_id}">{button_text}</button>
    <script>
    const el = document.getElementById("{button_id}");
    el.addEventListener("click", function() {{
        navigator.clipboard.writeText({text});
        el.textContent = 'Copied!';
        setTimeout(() => el.textContent = '{button_text}', 2000);
    }});
    </script>
    """
    components.html(f"{custom_css}{copy_code}", height=45)


if __name__ == "__main__":
    main()

the problem solved.

I dont undrestand why first version dosnt work and why it is working when I move  ' del st.session_state['edit_template_flag']' into edit_template function the problem solved.

please explain all I nedd to know about the place of set and rest or delet st.session_state