为什么我的validate_on_submit()不起作用?

时间:2019-12-06 17:37:39

标签: python flask flask-wtforms

我填写表格并单击“提交”后,文件未保存。表单为“提交失败”是可行的。已经花费了3个小时,却找不到问题

main.py

def gaussian_kernel(size: int,
                    mean: float,
                    std: float,
                   ):
    ''' Function to create a 2D gaussian Kernel for convolution;
    it assumes that the images are squared.
    ARGUMENTS:

        size: (int) half the dimension of the input image;
        mean: (float) mean value of the gaussian;
        std: (float) standard deviation of the mean;

    OUTPUT:

        a 2D Gaussian Kernel with shape (2*size, 2*size)'''

    d = tfp.distributions.Normal(mean, std)

    vals = d.prob(tf.range(start = -size, limit = size, dtype = tf.float32))

    gauss_kernel = tf.einsum('i,j->ij',
                                  vals,
                                  vals)

    return gauss_kernel / tf.reduce_sum(gauss_kernel)

@tf.function
def MyNorm(p, q, K, std, L, dim):
    """
    Fuction to compute Norm between two input images.
    ARGUMENTS

        p, q: (Tensor) input images with dimensions (1, dim, dim, 1);
        K = (Tensor) Gaussian Kernel produced with the gaussian_kernel function;
        std = (float) standard deviation of the Gaussian Kernel
        L = 
        dim: (int) images dimension

    OUTPUT

        w = (float) distance between p and q.
    """
    b = np.ones(shape=(dim, dim))
    b =  np.reshape(b, [-1, dim, dim, 1])
    b = tf.convert_to_tensor(b)
    pixel2 = np.tile(range(dim),dim)
    pixel1 = np.array([[i]*dim for i in range(dim)]).flatten()

    k = 0
    pixel2 = tf.convert_to_tensor(pixel2, dtype='float64')
    pixel1 = tf.convert_to_tensor(pixel1, dtype='float64')

    while k < L:
        a = q / tf.nn.depthwise_conv2d(b, K, strides=[1,dim, dim,1], padding='SAME')
        b = p / tf.nn.depthwise_conv2d(a, K, strides=[1,dim ,dim,1], padding='SAME')
        k+=1

    a = tf.reshape(a, shape=[-1])
    b = tf.reshape(b, shape=[-1])

    i = tf.Variable(0)
    w = tf.Variable(0)

    def cond(i):
        return(tf.less(i, dim**2))
    def body(i):
        j = tf.Variable(0)
        for j in range(i - 1):
            c_ij = np.sum((pixel1[i] -pixel2[j])**2)
            w.assign_add((a[i] * b[j] * c_ij) * math.exp(-c_ij / std) + (a[j] * b[i] * c_ij) * 
                        math.exp(-c_ij / std))
        i.assign_add(1)
        return i

    tf.while_loop(cond, body, [i])
    return w
dim = 256
std = 50.
w = Wass(p, q, K, std=std, L=10, dim=dim)

在路线中尝试不同的组合,但它们不起作用。

routes.py

def new_add_payment(id,summ,less,typer):
    timer = datetime.datetime.now()
    f = codecs.open(os.path.abspath('invoices') + '/' + str(id) + '$' + str(timer) + '.json', 'w', 'utf-8')
    payment = {'id': id, 'summ': summ, 'less': less, 'type': typer}
    f.write(str(payment))

我猜主要问题出在HTML文件中,但我无法弄清楚

payments_new.html

@app.route('/new_payment',methods = ['GET','POST',])
def new_add_payment():
    form = AddPaymentNew()
    if form.validate_on_submit():
        id = format(form.sub.data)
        summ = format(form.summ.data)
        lessons = format(form.summ.data)
        typer = request.form['options']
        main.new_add_payment(id,summ,lessons,typer)
        print('Submit successful')
        return render_template('ok.html')
    else:
        print('Fail to submit')
    return render_template('payment_new.html', title='NEW ADD PAYMENT',form=form)

2 个答案:

答案 0 :(得分:0)

这里没有足够的信息-您没有显示表单定义。为什么在调用Submit之前不打印出表单的内容(或使用调试器),以确保您的路由有效,并且所获得的数据就是您的想法。

使用您的附加信息-您的“提交”按钮不应包含任何验证器(因为它不传输任何数据)。 另外-form.errors列出了遇到的所有错误-按字段列出-我会打印出来。

答案 1 :(得分:0)

要精确检查验证失败的位置,可以在模板中添加这段代码,以方便调试过程

{% for error in form.errors %}

    <div class="alert alert-danger alert-dismissible">
    <p><i class="icon fas fa-ban"></i> Alert!</p>
        {{ error }} invalid
    </div>
{% endfor %}

此外,您的表单没有分配方法

<form action="/controller_method/" method="post">