How to insert 'checked' in input type radio in forms with flask

Viewed 212

my question is how to insert 'checked' to the radio input in Jinja2.

part of edituser.html

<input type="radio" name="level" value="user">User</input>
<input type="radio" name="level" value="admin">Admin</input>

var user passing information about user to render_template()

user = Users.query.filter_by(id=user_id).first()    
return render_template('admin/users/editUser.html', user=user)

I have an idea about create radio inputs inside my function and return it with another variable.. What is best practice?

1 Answers

You will need some type of condition of course. Since you did not provide any condition, let us assume that your user object has an attribute called is_admin. Let's also assume you want the User radio checked if the user is not an admin, and the Admin radio checked if they are.

You can template in the "checked" attribute to the input with an inline conditional statement.

<input type="radio" name="level" value="user" {{'checked' if not user.is_admin else ''}}>User</input>
<input type="radio" name="level" value="admin" {{'checked' if user.is_admin else ''}}>Admin</input>

If user.is_admin == True then the admin radio will be checked, otherwise the user radio will be.

Related