编辑表单不起作用

时间:2014-12-25 14:39:22

标签: flask flask-sqlalchemy flask-wtforms

圣诞快乐!!!!我使用flask 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)
  

model.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 %}

3 个答案:

答案 0 :(得分:0)

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

所以这应该是更正后的代码段

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()

答案 1 :(得分:0)

我在我的机器上尝试了你的代码。由于代码修改很少,我能够更新数据库。

请在下面找到更新的块:

@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 )

答案 2 :(得分:0)

我知道这是一个较旧的问题,但我是从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():

在遇到同样的问题时帮助了我。