I am working on building a simple app with Python Flask. I am having a problem with the button inside of this form. Users can comment and then push the button to post their comment.
When this button is clicked, the form action(this action in python, redirects to the current page.) is fired. Now, when the button is clicked, the comment is posted on the browser but the browser is refreshed. I don't want the browser to be refreshed every time when users post their comment. How should I make this button not to refresh the page and still post the comment and show the comment on the page without refreshing the page?
<form method="POST" action="{{ url_for('feed_app.message', message_id=fm.message.id) }}" role="form" enctype="multipart/form-data">
{{ form.hidden_tag() }}
<div class="form-group">
{{ form.post(class='form-control', rows=1, style="background-color:#ffffff;width:200px;display:inline-block;") }}
<input type="hidden" name="to_user" value="{{ user.username }}" />
<button style="border-radius:5px;" type="submit" class="btn btn-success">Comment</button>
</div>
</form>
This is the python code.
@feed_app.route('/message/<message_id>', methods=('GET', 'POST'))
def message(message_id):
form = FeedPostForm()
message = None
user = User.objects.get(username=session.get('username'))
message = Message.objects.filter(id=message_id).first()
if not message:
abort(404)
if message and message.parent:
abort(404)
if form.validate_on_submit() and session.get('username'):
# process post
from_user = User.objects.get(username=session.get('username'))
post = form.post.data
# write the message
comment = Message(
from_user=from_user,
text=post,
message_type=COMMENT,
parent=message_id
).save()
return redirect(url_for('home_app.home', message_id=message.id))
return render_template('feed/message.html',
message=message,
form=form
)
Is it because I set the message to redirect to the current page? I am not sure if this is an HTML problem or Flask problem.