Python url_for syntax error

Question:

I have a function to genereate new courses as below which takes 0 args if the course is new & 5 if it has just attempted to be created but failed validation.

The route:

@app.route('/courses/new')
def new_course(*args):
    if len(args) == 5:
        ...
    else:
        ...

The caller:

...
return redirect(url_for('new_course',  int(request.form['id']), course_code, semester, year, student_ids))

I get the error message url_for() takes 1 argument (6 given).
Or if I try:

...
return redirect(url_for('new_course',  args[int(request.form['id']), course_code, semester, year, student_ids]))

I get the error message new_course() takes 5 arguments (0 given)

What am I doing wrong?

Asked By: Cameron Simpson

||

Answers:

url_for takes key-values pairs as argument, for more info refer: http://flask.pocoo.org/docs/api/#flask.url_for

This will work:

@app.route('/courses/new/') # Added trailing slashes. For more check http://flask.pocoo.org/docs/api/#url-route-registrations
def new_course():
    # use request.args to fetch query strings
    # For example: id = request.args.get('id')

The caller:

return redirect(url_for('new_course',  id=int(request.form['id']), code=course_code, sem=semester, year=year, student_id=student_ids))
Answered By: rajpy
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.