Pass variable in url_for to Python function

Question:

I have Python/Flask project that displays a button called Tickets at the end of a list row. I am trying to pass proj_id in Jinja syntax to a Python function ‘tix(proj_id)’ where it will be used as an input to a SQL Alchemy query. The value project.id is an integer that is not null.

HTML:

<td class="text-end"><a href="{{ url_for('tix', proj_id=project.id) }}" class="btn btn-sm btn-primary">Tickets</a></td>

Python:

def tix(proj_id):
    tickets = Ticket.query.where(Ticket.project_id == proj_id)
    return render_template('ticket.html', allticket=tickets)

Clicking the Tickets button creates this error message:
TypeError: tix() missing 1 required positional argument: ‘proj_id’

Is the syntax incorrect or is there some other issue?

Asked By: NickNaym99

||

Answers:

did you add a variable to your route? like this :

@app.route("/ticket/<int:proj_id>")
def tix(proj_id):
    tickets = Ticket.query.where(Ticket.project_id == proj_id)
    return render_template('ticket.html', allticket=tickets)
Answered By: Shayan Sakha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.