7

I am having troubles with form validation. The country list is generated correctly, and previous forms worked fine. It is only breaking in POST requests.

Here is my forms.py:

from wtforms import Form, BooleanField, SelectField, \
                    StringField, PasswordField, SubmitField, validators, \
                    RadioField
from ..models import User
from pycountry import countries
...
## Account settings
# We get all COUNTRIES
COUNTRIES = [(c.name, c.name) for c in countries]
# edit profile
class ProfileForm(Form):
    username = StringField('name',[validators.Length(min=1, max=120), validators.InputRequired])
    email = StringField('email', [validators.Length(min=6, max=120), validators.Email()])
    company = StringField('name',[validators.Length(min=1, max=120)])
    country = SelectField('country', choices=COUNTRIES)
    news = BooleanField('news')

and here is the view:

@user.route('/profile/', methods=['GET', 'POST'])
@login_required
def profile():
    userid = current_user.get_id()
    user = User.query.filter_by(id=userid).first_or_404()
    print(user)
    form = ProfileForm(request.form)
    if request.method == 'POST' and form.validate():
        user.username = form.username.data
        ...
        return render_template('settings.html', form=form )
    else:
        form.username.data = user.username
        ...
        return render_template('settings.html', form=form )
7
  • in settings.html i am using {{ form.field}} to generate each form field Commented May 10, 2017 at 11:58
  • Try form = ProfileForm(request.POST) instead of ProfileForm(request.form). Would help if you provided the rest of the stack trace Commented May 10, 2017 at 12:01
  • I doesnt work. here is the stack trace: pastebin.com/Lq00syTz Commented May 10, 2017 at 12:28
  • If I print form.data everything seems fine: {'news': True, 'username': 'asdf', 'country': 'Aruba', 'company': 'asDf', 'email': '[email protected]'} Commented May 10, 2017 at 12:32
  • Check the form.errors dictionary to see if it contains anything. It could potentially be missing a CSRF key Commented May 10, 2017 at 12:38

1 Answer 1

28

It should be validators.InputRequired() instead of validators.InputRequired. Thanks @jackevans

Sign up to request clarification or add additional context in comments.

1 Comment

So much time waisted... it's a pitty Python does not catch such stupid mistakes earlier. Sometimes I am wondering how is it possible to build anything robust in dynamically-typed languages.. Thank you @jmrueda.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.