import streamlit as st
from firebase_admin import firestore
import datetime
def app():
if 'db' not in st.session_state:
st.session_state.db = ''
code
Assistant
db = firestore.client()
st.session_state.db = db
ph = ''
if st.session_state.username == '':
ph = 'Login to be able to post!!'
else:
ph = 'Post your Work'
post = st.text_area(label=' :orange[+ New Key Work Highlight]', placeholder=ph, height=None, max_chars=1000)
if st.button('Post', use_container_width=True):
if post != '':
info = db.collection('Posts').document(st.session_state.username).get()
current_time = datetime.datetime.now()
if info.exists:
info = info.to_dict()
if 'Content' in info.keys():
pos = db.collection('Posts').document(st.session_state.username)
pos.update({
u'Content': firestore.ArrayUnion([u'{}'.format(post)]),
'Last Modified': current_time
})
else:
data = {"Content": [post], 'Username': st.session_state.username, 'Last Modified': current_time}
db.collection('Posts').document(st.session_state.username).set(data)
else:
data = {"Content": [post], 'Username': st.session_state.username, 'Last Modified': current_time}
db.collection('Posts').document(st.session_state.username).set(data)
st.success('Work uploaded!!')
st.header(' :violet[Latest Work Highlights] ')
# Month selection
month_selection = st.selectbox("Select Month", ["All", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"])
docs = db.collection('Posts').get()
filtered_docs = []
# Filter documents based on the selected month
selected_month = month_selection.lower()
for doc in docs:
d = doc.to_dict()
d['Last Modified'] = d.get('Last Modified', datetime.datetime.now()) # Fallback in case it doesn't exist
# Store all the posts for the displayed month
if selected_month == "all" or d['Last Modified'].strftime("%B").lower() == selected_month:
filtered_docs.append(d)
# Sort by last modified date
filtered_docs.sort(key=lambda x: x['Last Modified'], reverse=True)
# Create a scrollable container
with st.container():
if filtered_docs:
for d in filtered_docs:
# Display each content item in the Content array
for content in d['Content']:
try:
st.markdown("""
<style>
.stTextArea [data-baseweb=base-input] [disabled=""]{
-webkit-text-fill-color: black;
}
</style>
""", unsafe_allow_html=True)
st.text_area(label=':green[Posted by:] '+':orange[{}]'.format(d['Username']),
value=content, height=200, disabled=True)
st.write(f"**Date Posted:** {d['Last Modified'].strftime('%Y-%m-%d %H:%M:%S')}")
except Exception as e:
st.write(f"Error displaying post: {e}")
else:
st.write("No posts available for this month.") in this the date posted is modifying each time we add a new post for all other exusting post also ...i wanted it to be the dtae and time at the time of posting that
The issue you're facing is due to the way you're currently updating the "Last Modified" timestamp. When you add a new post to an existing document, you are updating the timestamp for all posts associated with that document (for the user) instead of maintaining the timestamp for each individual post.
To solve this, you need to structure your Firestore database differently. Instead of storing all posts in a single document for each user, you could create a new document for each post. This way, each post can have its own "Last Modified" timestamp. Here’s how you can modify the code:
Change Document Structure: Instead of having a single document for each user, each post can be a separate document in the Posts collection.
Modify Post Logic: When a user posts something, create a new document with a unique ID rather than modifying an existing document.
Here’s how you can modify your code accordingly:
python
import streamlit as st
from firebase_admin import firestore
import datetime
def app():
if 'db' not in st.session_state:
st.session_state.db = firestore.client()
db = st.session_state.db
ph = ''
if st.session_state.username == '':
ph = 'Login to be able to post!!'
else:
ph = 'Post your Work'
post = st.text_area(label=' :orange[+ New Key Work Highlight]', placeholder=ph, height=None, max_chars=1000)
if st.button('Post', use_container_width=True):
if post != '':
current_time = datetime.datetime.now()
data = {
'Content': post,
'Username': st.session_state.username,
'Last Modified': current_time
}
# Create a new document in the Posts collection
db.collection('Posts').add(data)
st.success('Work uploaded!!')
st.header(' :violet[Latest Work Highlights] ')
# Month selection
month_selection = st.selectbox("Select Month", ["All", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"])
docs = db.collection('Posts').get()
filtered_docs = []
# Filter documents based on the selected month
selected_month = month_selection.lower()
for doc in docs:
d = doc.to_dict()
d['Last Modified'] = d.get('Last Modified', datetime.datetime.now()) # Fallback in case it doesn't exist
if selected_month == "all" or d['Last Modified'].strftime("%B").lower() == selected_month:
filtered_docs.append(d)
# Sort by last modified date
filtered_docs.sort(key=lambda x: x['Last Modified'], reverse=True)
# Create a scrollable container
with st.container():
if filtered_docs:
for d in filtered_docs:
try:
st.text_area(label=':green[Posted by:] '+':orange[{}]'.format(d['Username']),
value=d['Content'], height=200, disabled=True)
st.write(f"**Date Posted:** {d['Last Modified'].strftime('%Y-%m-%d %H:%M:%S')}")
except Exception as e:
st.write(f"Error displaying post: {e}")
else:
st.write("No posts available for this month.")
Key Changes:
Instead of updating an existing document, we are now using db.collection('Posts').add(data) to create a new document for each post.
Removed the logic that checks if the document exists; every post will now be a new document, and each will have its distinct timestamp.
This way, every post will retain its own "Last Modified" timestamp independent of other posts.