python - Disabled field is considered for validation in WTForms and Flask -


i have fields in page disabled example:(using jinja2 templating system)

<html> <body> <form action="" method=post>     {{ form.name(disabled=true) }}     {{ form.title }}     -- submit button -- </form> </body> </html> 

field disabled in form expected.

in views.py: on doing validate_on_submit() on form submit, fails validation error on 'name' field disabled. hoping validation ignores disabled field. right behaviour? if so, can please let know how handle such case?

updated:

class teamform(wtf.form):     name = wtf.textfield("team name", validators=[validators.required()])     title = wtf.textfield("title", validators=[validators.required()]) 

this interesting problem, , way wtforms solves intentionally requires explicitness, because has security , not allowing users fake input.

so intent is, "managers" cannot edit name, while "admins" can.

at first glance seems obvious, disable field in html, , write view this:

def edit_team():     form = teamform(request.post, obj=team)     if request.post , form.validate():         form.populate_obj(team) # <-- dangerous part here         return redirect('/teams')     return render('edit_team.html') 

as written, major security risk, because the disabled property in html forms client-side only. html inspector (ie firebug, webkit document inspector, etc) can remove property, or make request so:

post /edit_team/7 http/1.0 content-type: application/x-urlencoded  team=evilteamname&title=foo 

the issue of course, how gate on server-side, corresponding appropriate way of doing this? correct approach wtforms not have field in first place. there's few ways this, 1 use form composition , have e.g. managerteamform , adminteamform (sometimes better) other times it's easier use del remove specific fields.

so here's how write view, , not have validation issues:

def edit_team():     form = teamform(request.post, obj=team)     if user.role == 'manager':         del form.name     if request.post , form.validate():         form.populate_obj(team)         return redirect('/teams')     return render('edit_team.html') 

and quick modification template:

<html> <body> <form action="" method=post>     {% if 'name' in form %}         {{ form.name() }}     {% else %}         {{ team.name|e }}     {% endif %}     {{ form.title }}     -- submit button -- </form> </body> </html> 

some pieces of reference wtforms best-practices:


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -