[FIXED] Pass variable in url_for to Python function

Issue

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?

Solution

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

Answer Checked By – Robin (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published