首页 > 解决方案 > WTF form.validate_on_submit() 奇怪的问题

问题描述

当我单击提交按钮时,我的表单验证等于 True,但没有显示任何内容。问题是,如果我再次按下提交按钮,那么一切都会显示,并且我不再需要继续单击按钮两次。直到我再次重新启动服务器。我很困惑,如果有人能告诉我我做错了什么,我将不胜感激。

如果我要删除该validate_on_submit()功能,则表单可以正常工作,但无法验证。这是我不想要的。

编辑 1 我已将print('------ {0}'.format(request.form))和添加print(form.errors)到我的代码中以进行调试。

当我将值插入表单print('------ {0}'.format(request.form))时,它会打印出以下内容:

------ ImmutableMultiDict([('csrf_token', 'IjFiMDE3OGVlZjVjYTYzODQ0MGE2MGMyYWI5NWFjOWYwNjZjMjlmN2Ii.YMFPNw.UtuYhwUnCAlmzdsGNaTEFPM9eek'), ('name', 'Bitcoin'), ('intial_investment', '1500'), ('coin_price', '500'), ('submit', 'Submit')])

虽然print(form.errors)打印以下内容:

{'csrf_token': ['The CSRF token is invalid.']}

我想相信我的问题的根本原因是由于 CSRF 无效。

但是,上面列出的实际令牌怎么会无效呢?

编辑 2

我已删除{{ form.csrf_token() }}request.form。因为我在实例化表单时不需要传递请求。

但是,原来的问题仍然存在。

我的路线.py

@application.route("/", methods=["GET", "POST"])

def home():
    form = Crypto_Form()
    coins = None
    print('------ {0}'.format(request.form))
    print(form.errors)
    if form.validate_on_submit():
        try:
            
            TWOPLACES = Decimal(10) ** -2
            Decimal('3.214').quantize(TWOPLACES)
            user_input = form.name.data
            coin_name = user_input.lower().replace(" ", "-")
            coin_gecko_name = cg.get_coins_markets(vs_currency='usd', ids=[coin_name.lower()], order='market_cap_desc', per_page='1', page='1', sparkline='false')[0]
            initial_investment = form.intial_investment.data
            coin_image = cg.get_coins_markets(vs_currency='usd', ids=[coin_name.lower()], order='market_cap_desc', per_page='1', page='1', sparkline='false')[0]
            coin_price = float(cg.get_price(ids=[coin_name.lower()], vs_currencies='usd')[coin_name.lower()]['usd'])
            presale_price = form.coin_price.data
            multiplier = Decimal(float(coin_price) / float(presale_price)).quantize(TWOPLACES)
            profit = round((float(initial_investment) / float(presale_price)) * float(coin_price))
            twenty_four_hour_change = Decimal(cg.get_price(ids=[coin_name.lower()], vs_currencies='usd', include_24hr_change='true')[coin_name.lower()]['usd_24h_change']).quantize(TWOPLACES)
            ath = cg.get_coins_markets(vs_currency='usd', ids=[coin_name.lower()], order='market_cap_desc', per_page='1', page='1', sparkline='false')[0]
            ath_change_percentage = cg.get_coins_markets(vs_currency='usd', ids=[coin_name.lower()], order='market_cap_desc', per_page='1', page='1', sparkline='false')[0]
            
            coin = Coin(
                        crypto_name=coin_gecko_name['name'],
                        coin_initial_invesment=initial_investment,
                        image=coin_image['image'],
                        current_price=coin_price,
                        presale_price=presale_price,
                        multiple= multiplier,
                        profit=profit,
                        twenty_four_hour=twenty_four_hour_change,
                        all_time_high=ath['ath'],
                        all_time_percentage_change=Decimal(ath['ath_change_percentage']).quantize(TWOPLACES)
                        )

            db.session.add(coin)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print('Failed to add coin')
            print(e)
            
    coins = Coin.query.all()
    coin_profit = Coin.query.with_entities(func.sum(Coin.profit).label('total')).first().total
    if coin_profit is None:
        coin_profit = 0
    
    return render_template("home.html", coins=coins, value=coin_profit, form=form)

我的表格.py

class Crypto_Form(Form):
    name = StringField("Enter Coin Name", [validators.DataRequired(message="Please enter the Crypto Currency name.")])
    intial_investment = DecimalField("Enter Initial Investment", [validators.DataRequired(message="Please enter a number")])
    coin_price = DecimalField("Enter Coin Price", [validators.DataRequired(message="Please enter a number")])
    submit = SubmitField("Submit")

我的神社表格

<form class="justify-content-center" method="POST" name="Crypto_Info" role="form">
        
            {{ form.hidden_tag() 

            <div class="form-group">
                {{ form.name.label(class="form-control-label") }}
                {% if form.name.errors %}
                    {{ form.name(class="form-control form-control-lg is-invalid")}}
                    <div class="invalid-feedback">
                        {% for error in form.name.errors %}
                            <span>{{ error }}</span>
                        {% endfor %}
                    </div>
                {% else %}
                    {{ form.name(class="form-control form-control-lg") }}
                {% endif %}
            </div>
            <div class="form-group">
                {{ form.intial_investment.label(class="form-control-label") }}
                {% if form.intial_investment.errors %}
                    {{ form.intial_investment(class="form-control form-control-lg is-invalid")}}
                    <div class="invalid-feedback">
                        {% for error in form.intial_investment.errors %}
                            <span>{{ error }}</span>
                        {% endfor %}
                    </div>
                {% else %}
                    {{ form.intial_investment(class="form-control form-control-lg") }}
                {% endif %}
            </div>
            <div class="form-group">
                {{ form.coin_price.label(class="form-control-label") }}
                {% if form.coin_price.errors %}
                    {{ form.coin_price(class="form-control form-control-lg is-invalid")}}
                    <div class="invalid-feedback">
                        {% for error in form.coin_price.errors %}
                            <span>{{ error }}</span>
                        {% endfor %}
                    </div>
                {% else %}
                    {{ form.coin_price(class="form-control form-control-lg") }}
                {% endif %}
            </div>
            <div>
                {{ form.submit(class="btn btn-primary") }}
            </div>
        
        </form> 

标签: pythonpython-3.xflaskflask-wtformsflask-restful

解决方案


推荐阅读