I am working on a notification system on my website. I decided to make a model in the database for them. I also made a function in views.py that takes an argument of a user that is receiving a notification and the type of notification. Here is the code:
@views.route('/send_notification',methods = ['GET','POST']) @login_required def send_notification(user, type): reciever = User.query.filter_by(username = user).first() if type == 'family-invitation': family = Family.query.filter_by(id = current_user.family_id).first() description = "invites you to their family!" new_notification = Notification(sender = current_user.username, sender_prof_img = family.prof_img, user_id = reciever.id, description = description) db.session.add(new_notification) db.session.commit() flash("Invitation to family has been sent!", category="success") return True
Now I want to be able to send the user a notification when someone invites them. I was thinking about calling the python function when someone presses the button but I don’t know how to code it.
I came up with something like this but it doesn’t work:
<button onclick="window.location.href = '{{ url_for('views.send_notification(profileUser.username, 'family-invitation')') }}';" > Invite to family </button>
Advertisement
Answer
url_for() in Flask Jinja templates does not work like that. It forms a URL to a specific resource, which means you can not pass Python code as a parameter. The option that comes to my mind first is to use URL parameters for passing data to your route function.
@views.route('/send_notification/<user>/<type>',methods = ['GET','POST']) @login_required def send_notification(user, type): reciever = User.query.filter_by(username = user).first() if type == 'family-invitation': family = Family.query.filter_by(id = current_user.family_id).first() description = "invites you to their family!" new_notification = Notification(sender = current_user.username, sender_prof_img = family.prof_img, user_id = reciever.id, description = description) db.session.add(new_notification) db.session.commit() flash("Invitation to family has been sent!", category="success") return True
So that your HTML would look like that:
<button onclick="btnOnClick(profileUser.username, 'family-invitation');" > Invite to family </button> <script> function btnOnClick(username, notificationType) { window.location = `/send_notification/${username}/${notificationType}`; } </script>