user1592380
user1592380

Reputation: 36367

Conditional WTFform fields

I'm working on a flask app and using flask-wtf to help manage my forms. I have the following simplified form:

<form id="registerForm" class="form form-register" method="POST" action="" role="form">
        {{ form.hidden_tag() }}
        <div class="form-group">
            {{form.username.label}}
            {{form.username(placeholder="Username", class_="form-control")}}
        </div>
        <div class="form-group">
            {{form.email.label}}
            {{form.email(placeholder="Email", class_="form-control")}}
        </div>
        <div class="form-group">
            {{form.password.label}}
            {{form.password(placeholder="Password", class_="form-control")}}

There are 2 ways to register on the site - Either with or without an email token.

If the email has been confirmed the user gets an email containing:

http://127.0.0.1:5000/register/ImNsdWVtYXJpbmUzQG1haWxpbmF0b3IuY29tIg.Ca9oUQ.bRJmGYQ1wNqfcQFx1pYyoCEy2oM

Otherwise on the site itself the user could click on:

 http://127.0.0.1:5000/register

The following code can handle both cases:

@blueprint.route("/register/", defaults={'token': ''}, methods=['GET', 'POST'])
@blueprint.route("/register/<token>", methods=['GET', 'POST'])
def register(token):
    form = RegisterForm(request.form, csrf_enabled=False)
    email = confirm_token(token)
    if form.validate_on_submit():
        new_user = User.create(username=form.username.data,
                              email=form.email.data,
                               password=form.password.data,
                               active=True)

If a token is used, I would like to display and validate only 2 form fields (username, password) . If no token - all 3 . How can this be done?

Upvotes: 0

Views: 349

Answers (1)

micgeronimo
micgeronimo

Reputation: 2149

You can create two forms for this, first BaseRegistrationForm with username, password and SomeOtherForm which will inherit from first and have own email field. For me it seems like better approach because it will be more understandable when a year later someone will have to read your code(even you)

Upvotes: 1

Related Questions