【问题标题】:edit the form is not working编辑表格不起作用
【发布时间】:2023-03-05 20:11:01
【问题描述】:

圣诞快乐!!!!我使用烧瓶 sqlalchemy 和 wtf。我可以创建新的并显示在 info.html 但是当我尝试编辑表单时,数据库中没有变化所以它不起作用。所以我想知道问题在哪里?

app.py

    #With this route I can add new form in database 
    @app.route('/contact', methods=['GET', 'POST'])
    def contact():
      form = LoginForm(request.form)
      if request.method == 'POST':
          if form.validate()== True:
              contact = Contacts()
              # populate the model
              form.populate_obj(contact)
              db.session.add(contact)
              db.session.commit()
              # Contact commited to database
              # RETURN TO INFO.HTML
              return redirect(url_for('info'))

           else:
              #If the form does not have all fields that are required 
              return render_template('contact.html', form=form)

    # This is the part for edit which is not working
    # so I query and populate it but no change none in 
    # database none in info.html
    @app.route('/edit/<int:id>', methods=['POST']) 
    def edit(id=None):
        user = Contacts.query.get_or_404(id)  
        form = LoginForm(request.form,obj=user) 
        # check the validate and then populate the obj  
        if form.validate_on_submit()== True:
           #populate it
           form.populate_obj(user)
           db.session.commit()
           return redirect(url_for('info'))
        else: 
            #If the form does not have all fields that are required 
            return render_template('edit.html', id=id )
    @app.route('/edit/<int:id>', methods=['GET'])
   def profile(id=None):
  user = Contacts.query.get_or_404(id)
  form = LoginForm(request.form, obj=user)
  return render_template('edit.html',form=form, id =id)
    # this route to html that should show all info
    @app.route('/info', methods=['GET', 'POST'])
    def info():
        #query all
        info = Contacts.query.all()
        return render_template('info.html', contact=info)

模型.py

 # model with table name Contacts
 class Contacts(db.Model):
       __tablename__ = "Contacts"
       id = db.Column(db.Integer, primary_key = True)
       name = db.Column(db.String(50))
       email = db.Column(db.String(50))
       age = db.Column(db.Integer)

form.py

# this is the form wtf
Class LoginForm(Form):
        name = StringField("Name", [validators.Required("Please enter your name.")])
        email = StringField("Email", [validators.Required("Please enter your email address."), validators.Email("Please enter valid email address.")])
        age = IntegerField("age", [validators.Required("Please enter your age.")])
        submit = SubmitField("Submit")

info.html

 # it should display all updated form But it wont??
    {% extends "layout.html" %}
    {% block content %}
         <h2>show the info</h2>
             {% for contact in contact  %} # Maybe this is also Problem?
               <strong>name:</strong> {{ contact.name}} <br>
               <strong>email:</strong> {{ contact.email }} <br>
               <strong>age:</strong> {{ contact.age}} <br>
               <br>
               {% endfor %}

      {% endblock %}

【问题讨论】:

  • 仍然没有好的答案有什么帮助吗?
  • 表格是否有效?这样您就可以使用 sqlalchemy 进行实际操作了?
  • 当验证不起作用时,您永远不会更新。因为只有在可能验证表单时才会更新。
  • Thanx,我知道我的意思是为什么数据库没有变化帮助我解决这个问题@muthan

标签: flask flask-sqlalchemy flask-wtforms


【解决方案1】:

我知道这是一个较老的问题,但我引用的是 Why doesn't my WTForms-JSON form update correctly?

本质上,您需要先初始化表单,然后检查它是否已提交:

form = FormBuilder()
if not form.is_submitted():

    form = FormBuilder.populate_obj(obj)
else:
    form = FormBuilder() # will populate from submitted data

if form.validate_on_submit():

它在遇到同样问题时对我有帮助。

【讨论】:

    【解决方案2】:

    我在我的机器上试过你的代码。只需稍加修改代码,我就可以更新数据库。

    请在下面找到更新的块:

    @app.route('/edit/<int:id>', methods=['POST'])
    def submit(id=None):
        user = Contacts.query.get_or_404(id)
        form = LoginForm(request.form,obj=user)
        #return render_template('edit.html', form=form, id=1 )
        if form.validate() == True:
            form.populate_obj(user)
            db.session.commit()
            return redirect(url_for('info'))
        else:
            return redirect(url_for(edit, id=id))
    
    @app.route('/edit/<int:id>', methods=['GET'])
    def edit(id=None):
        user = Contacts.query.get_or_404(id)
        form = LoginForm(request.form,obj=user)
        return render_template('edit.html', form=form, id=id )
    

    【讨论】:

    • 我试试你的新的但是数据库还是没有变化知道吗?@ Deepak Kumar Mangal
    • 也许它没有连接到数据库不知道但我可以添加新的(路由联系人)正在工作所以不知道@Deepak Kumar Mangal
    • @Linda 它对我来说工作正常。您能否分享您的完整代码,以便我尝试调试?
    • 现在更新,如果你能帮助@Deepak Kumar Mangal,真的很感激
    【解决方案3】:

    您不必在每次查询时读取对象。 Queryobject 绑定到会话。因此,您只需要commit 更改,而不需要再次add

    所以这应该是更正后的代码 sn-p

    user = Contacts.query.get_or_404(id)  
        form = LoginForm(request.form,obj=user) 
        # check the validate and then populate the obj  
        if form.validate()== True:
            # populate it
            form.populate_obj(user)
            db.session.commit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2023-03-25
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      相关资源
      最近更新 更多