我在MongoDB上使用烧瓶,我在app.py中有一个名为/ announcements的路由,此公告的作用类似于留言板,用户可以在其中张贴消息,并且用户可以阅读这些消息。这有一些警告。
首先,我看到用户消息正在存储在我的数据库(即MongoDB)中,但是当用户单击表单上的“提交”按钮时,页面似乎已刷新,但我不相信这确实是我通常必须要做的手动刷新页面,然后我将在页面上看到用户消息发布。
第二个问题是当我手动刷新页面时,在创建的留言板上看到同一用户帖子的重复条目。最初,我只会看到一个帖子,但是随着发布的帖子越多,刷新页面越多,重复的次数就越多。
# Announcements
@app.route('/announcements', methods=['GET', 'POST'])
@login_required
def announcements():
# get current user
for cur_user in User.objects:
cur_user = cur_user.username
# msg title info from db
msg_title_list = []
for msg_title in Announcement.objects.order_by('-pub_date'):
msg_title = msg_title.title
msg_title_list.append(msg_title)
# get msg text from db
msg_text_list = []
for msg_text in Announcement.objects.order_by('-pub_date'):
msg_text = msg_text.text
msg_text_list.append(msg_text)
# get msg date from db
pub_date_list = []
for pub_date in Announcement.objects.order_by('-pub_date'):
pub_date = pub_date.pub_date
pub_date_list.append(pub_date)
# get username from db
user_name_list = []
for username in Announcement.objects.order_by('-pub_date'):
username = username.username
user_name_list.append(username)
if request.method == 'POST':
# get form data
message_title = request.form['message_title']
message_text = request.form['message_text']
# push msg info into db
Announcement(username=cur_user, title=message_title, text=message_text).save()
return render_template('announcements.html', cur_user=cur_user, msg_data=zip(msg_title_list,
msg_text_list,
pub_date_list,
user_name_list))
<div class="content-list-body">
{% for msg_title_list, msg_text_list, pub_date_list, user_name_list in msg_data%}
<div class="card card-note">
<div class="card-header">
<div class="media align-items-center">
<img alt="Peggy Brown" src="static/img/avatar-female-2.jpg" class="avatar" data-toggle="tooltip" data-title="{{user_name_list}}" data-filter-by="alt" />
<div class="media-body">
<h6 class="mb-0" data-filter-by="text">{{msg_title_list}}</h6>
</div>
</div>
<div class="d-flex align-items-center">
<span data-filter-by="text">{{pub_date_list}}</span>
<div class="ml-1 dropdown card-options">
<button class="btn-options" type="button" id="note-dropdown-button-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="material-icons">more_vert</i>
</button>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="#">Edit</a>
<a class="dropdown-item text-danger" href="#">Delete</a>
</div>
</div>
</div>
</div>
<div class="card-body" data-filter-by="text">
<p>{{msg_text_list}}</p>
</div>
</div>
{% endfor %}
</div>