WillB WillB - 4 months ago 15
Python Question

Get kwargs passed to url_for in Flask view

I am passing some kwargs to

url_for
, but
**kwargs
in the view function isn't getting them. How do I get the extra data?

File
admin.py



@admin_bp.route('/alerts', methods=['GET'])
def display_alerts(**kwargs):
print kwargs
alert_sorted = Alert.query.filter_by(**kwargs).all()


index.html
<a href="{{ url_for('admin.display_alerts', {'user_id':val.user_id} )}}">Show User Alerts</a>


File
models.py



class Alert(db.Model):
__tablename__ = 'alert'
__table_args__ = {'extend_existing': True}

alert_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
user_id = db.Column(db.BigInteger, db.ForeignKey('users.user_id'), nullable=False)
name = db.Column(db.String(ALERT_NAME_MAX_SIZE), nullable=False)


I cannot modify the function
display_alerts(**kwargs)
because it is used by a lot of other functions. My issue is to understand how to send
kwargs
arguments into the
url_for()
function in HTML.

Answer

You're looking for request.args. Any unknown keywords arguments passed to url_for will be used to populate the query string. The query string is then exposed through request.args.

@admin_bp.route('/alerts')
@admin_auth
def display_alerts():
    print(request.args)