Flask WTForms提交按钮完全不起作用。

huangapple go评论58阅读模式
英文:

Flask WTForms submit button not working at all

问题

I can help you with the translation of the code, but it seems like you have a technical issue with your code. If you need assistance with debugging the code, I recommend posting your issue on a platform like Stack Overflow, where developers can provide specific assistance. Here's the translation of your provided code:

我可以帮你翻译这段代码但似乎你的代码存在技术问题如果你需要帮助调试代码我建议在类似 Stack Overflow 的平台上发布你的问题那里的开发者可以提供具体的帮助以下是你提供的代码的翻译

__init__.py

```python
from flask import Flask, render_template 
from flask_sqlalchemy import SQLAlchemy    # 使用类创建表

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///market.db'
app.config['SECRET_KEY'] = 'b61198e1258118d75478e8e4'
db = SQLAlchemy(app)

from market import routes

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField

class RegisterForm(FlaskForm):
    username = StringField(label='输入你的用户名:')
    email_address = StringField(label='电子邮件:')
    pw1 = PasswordField(label='密码:')
    pw2 = PasswordField(label='确认密码:')
    submit = SubmitField(label='创建帐户')

models.py

from market import db

class User(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(length=18), nullable=False, unique=True)
    email_address = db.Column(db.String(length=40), nullable=False, unique=True)
    password_hash = db.Column(db.String(length=60), nullable=False)
    budget = db.Column(db.Integer(), nullable=False, default=1000)
    items = db.relationship('Item', backref='owned_user', lazy=True)

    def __repr__(self):
        return f"用户: {self.name}"

routes.py

from market import app
from flask import Flask, render_template, redirect, url_for
from market.models import Item, User
from market.forms import RegisterForm
from market import db

@app.route('/register', methods=['GET', 'POST'])
def register_page():
    form = RegisterForm()
    if form.validate_on_submit():
        user_to_create = User(username=form.username.data,
                              email_address=form.email_address.data,
                              password_hash=form.pw1.data)    
        db.session.add(user_to_create)
        db.session.commit()
        return redirect(url_for('market_page'))

    return render_template('register.html', form=form)

run.py

from market import app

if __name__ == '__main__':
    app.run(debug=True)

templates 文件夹:

register.html

{% extends 'base.html' %}
{% block title %}
    注册
{% endblock %}   
{% block content %}
<body class='text-center'>
    <div class="container">
        <form method="POST" action="/market" class="form-register" style="color:white">
            {{ form.hidden_tag() }}
            <img class="mb-4" src="" alt="">
            <h1 class="h3 mb-3 font-weight-normal">
                请创建您的帐户
            </h1>
            <br>
            
            {{ form.username.label() }}
            {{ form.username(class="form-control", placeholder="用户名") }}
            
            {{ form.email_address.label() }}
            {{ form.email_address(class="form-control", placeholder="电子邮件地址") }}
            
            {{ form.pw1.label() }}
            {{ form.pw1(class="form-control", placeholder="密码") }}
            
            {{ form.pw2.label() }}
            {{ form.pw2(class="form-control", placeholder="确认密码") }}
            
            <br>
            
            {{ form.submit(class="btn btn-lg btn-block btn-primary") }} 
        </form>
    </div>
</body>  
{% endblock %}  

base.html

<!doctype html>
<html lang="en">
   <head>
      <!-- 必需的元标记 -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <title>
        {% block title %}

        {% endblock%}
      </title>
   </head>
   <body>
      <nav class="navbar navbar-expand-md navbar-dark bg-dark">
        <a class="navbar-brand" href="#">Flask Market</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav mr-auto">
              <li class="nav-item active">
                  <a class="nav-link" href="{{ url_for('home_page') }}">主页 <span class="sr-only">(当前)</span></a>
              </li>
              <li class="nav-item">
                  <a class="nav-link" href="{{ url_for('market_page') }}">市场</a>
              </li>
          </ul>
          <ul class="navbar-nav">
              <li class="nav-item">
                  <a class="nav-link" href="#">登录</a>
              </li>
              <li class="nav-item">
                  <a class="nav-link" href="{{ url_for('register_page') }}">注册</a>
              </li>
          </ul>
        </div>
      </nav>
        {% block content %}

        {% endblock %}
   </body>
   <style>
      body {
      background-color: #212121;
      color: white
      }
   </style>
</html>

你提供的代码翻译如上。如果你需要帮助解决代码问题,请提供更多细节,或在开发者社区上寻求帮助。

英文:

I'm trying to make a registeration page using WTForms but I'm having difficulties getting the submit button to work. When I fill all the page's fields and click the 'Submit' button nothing happens whatsoever, I checked the database to see if the form instance was even created and it wasn't, I also don't get redirected to the desired URL after submitting.

I'm currently following a Flask tutorial for Python on YT by JimShapedCoding Link to video

Here's my code:

init.py

from flask import Flask, render_template 
from flask_sqlalchemy import SQLAlchemy    #tables using classes
app = Flask(__name__)
app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = &#39;sqlite:///market.db&#39;
app.config[&#39;SECRET_KEY&#39;] = &#39;b61198e1258118d75478e8e4&#39;
db = SQLAlchemy(app)
from market import routes

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
class RegisterForm(FlaskForm):
username = StringField(label=&#39;Enter your username:&#39;)
email_address = StringField(label=&#39;Email:&#39;)
pw1 = PasswordField(label=&#39;Password:&#39;)
pw2 = PasswordField(label=&#39;Confirm Password:&#39;)
submit = SubmitField(label=&#39;Create Account&#39;)

models.py

from market import db
class User(db.Model):
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(length=18), nullable=False, unique=True)
email_address = db.Column(db.String(length=40), nullable=False, unique=True)
password_hash = db.Column(db.String(length=60), nullable=False)
budget = db.Column(db.Integer(), nullable=False, default=1000)
items = db.relationship(&#39;Item&#39;, backref=&#39;owned_user&#39;, lazy=True)
def __repr__(self):
return f&quot;Item: {self.name}&quot;

routes.py

from market import app
from flask import Flask, render_template, redirect, url_for
from market.models import Item, User
from market.forms import RegisterForm
from market import db
@app.route(&#39;/register&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def register_page():
form = RegisterForm()
if form.validate_on_submit():
user_to_create = User(username=form.username.data,
email_address=form.email_address.data,
password_hash=form.pw1.data)    
db.session.add(user_to_create)
db.session.commit()
return redirect(url_for(&#39;market_page&#39;))
return render_template(&#39;register.html&#39;, form=form)

run.py

from market import app
if __name__ == &#39;__main__&#39;:
app.run(debug=True)

templates folder:

register.html

{% extends &#39;base.html&#39; %}
{% block title %}
Register 
{% endblock %}   
{% block content %}
&lt;body  class=&#39;text-center&#39;&gt;
&lt;div class=&quot;container&quot;
&lt;form method=&quot;POST&quot; action=&quot;/market&quot; class=&quot;form-register&quot; style=&quot;color:white&quot;&gt;
{{ form.hidden_tag() }}
&lt;img class=&quot;mb-4&quot; src=&quot;&quot; alt=&quot;&quot;&gt;
&lt;h1 class=&quot;h3 mb-3 font-weight-normal&quot;&gt;
Please Create your Account
&lt;/h1&gt;
&lt;br&gt;
{{ form.username.label() }}
{{ form.username(class=&quot;form-control&quot;, placeholder=&quot;Username&quot;) }}
{{ form.email_address.label() }}
{{ form.email_address(class=&quot;form-control&quot;, placeholder=&quot;Email Address&quot;) }}
{{ form.pw1.label() }}
{{ form.pw1(class=&quot;form-control&quot;, placeholder=&quot;Password&quot;) }}
{{ form.pw2.label() }}
{{ form.pw2(class=&quot;form-control&quot;, placeholder=&quot;Confirm Password&quot;) }}
&lt;br&gt;
{{ form.submit(class=&quot;btn btn-lg btn-block btn-primary&quot;) }} 
&lt;/form&gt;
&lt;/div&gt;
&lt;/body&gt;  
{% endblock %}  

base.html

&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;!-- Required meta tags --&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
&lt;title&gt;
{% block title %}
{% endblock%}
&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;nav class=&quot;navbar navbar-expand-md navbar-dark bg-dark&quot;&gt;
&lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;Flask Market&lt;/a&gt;
&lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarNav&quot;&gt;
&lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;
&lt;/button&gt;
&lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarNav&quot;&gt;
&lt;ul class=&quot;navbar-nav mr-auto&quot;&gt;
&lt;li class=&quot;nav-item active&quot;&gt;
&lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for(&#39;home_page&#39;) }}&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;
&lt;/li&gt;
&lt;li class=&quot;nav-item&quot;&gt;
&lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for(&#39;market_page&#39;) }}&quot;&gt;Market&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;ul class=&quot;navbar-nav&quot;&gt;
&lt;li class=&quot;nav-item&quot;&gt;
&lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Login&lt;/a&gt;
&lt;/li&gt;
&lt;li class=&quot;nav-item&quot;&gt;
&lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for(&#39;register_page&#39;) }}&quot;&gt;Register&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;/nav&gt;
{% block content %}
{% endblock %}
&lt;/body&gt;
&lt;style&gt;
body {
background-color: #212121;
color: white
}
&lt;/style&gt;
&lt;/html&gt;

Photo of my project layout

How the registeration page looks like

After revising my code multiple times & making sure it's like what was in the video, I still couldn't manage to fix my issue or even impact it.

What I tried:

I tried using app.app_context().push()

before the db.session.add(user_to_create)
line in routes.py

I made sure all the variable names matched

I tried running it using $env:FLASK_APP = 'init.py' followed by flask run

This is how my terminal looks like whenever the page is refreshed:

127.0.0.1 - - [10/Apr/2023 23:09:02] "GET /register HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2023 23:09:11] "GET /favicon.ico HTTP/1.1" 404 -

If anyone may offer some help that'll be wonderful as I have been trying to debug this issue for around 3 days now.

答案1

得分: 0

Your code contains a typo in the register.html file. The div element that encloses the form is missing the trailing &gt; before the form element begins.

&lt;div class=&quot;container&quot;&gt;
    &lt;!-- Your form here. --&gt;
&lt;/div&gt;
英文:

Your code contains a typo in the register.html file. The div element that encloses the form is missing the trailing &gt; before the form element begins.

&lt;div class=&quot;container&quot;&gt;
    &lt;!-- Your form here. --&gt;
&lt;/div&gt;

huangapple
  • 本文由 发表于 2023年4月11日 05:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定