尝试更新数据库中的数据时,我一直遇到UNIQUE约束失败。我使用username作为primary_key,但是当我构造一个对象并将其添加到终端中的数据库时,这段代码工作得很好。只有当我在views.py中尝试它时才会遇到问题。
这是错误
IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: mobility.username [SQL: u'INSERT INTO mobility (username, cc_letter, sabc_cbt) VALUES (?, ?, ?)'] [parameters: (u'pass', u'tt', None)]
File "/home/jsnyder10/Documents/45/app/views.py", line 57, in mobility_edit_user
db.session.commit()
views.py - 这是造成db.session.commit()
问题的原因@app.route('/mobility_edit_user', methods=['GET', 'POST'])
@login_required
def mobility_edit_user():
#build user list
data=User.query.with_entities(User.username).all()
users=[]
for i in data:
users.append(i[0])
form=MobilityForm(request.form)
if request.method == "POST":
if request.form['submit']=='SelectUser':
#moves selected user to front of form to persist with next call
users.insert(0, users.pop(users.index(request.form.get('user'))))
data=Mobility.query.filter_by(username=request.form.get('user')).first()
#form.populate_obj(data)
form=MobilityForm(obj=data)
flash("Selected User " + request.form.get('user'))
elif request.form['submit']=='Update' and form.validate():
print("validated")
u=Mobility()
form.populate_obj(u)
u.username=request.form.get('user')
db.session.add(u)
print("added")
db.session.commit()
flash("Updated User" + request.form.get('user'))
else:
#move selected user to front of form
users.insert(0, users.pop(users.index(request.form.get('user'))))
data=Mobility.query.filter_by(username=request.form.get('user')).first()
form=MobilityForm(obj=data)
flash("Form not validated")
elif request.method == "GET":
form=MobilityForm(request.form)
flash("GET")
return render_template('mobility_edit_user.html',title='Mobility Edit User',
form=form, users=users)
models.py
class MobilityForm(ModelForm):
class Meta:
model=Mobility
forms.py
class MobilityForm(ModelForm):
class Meta:
model=Mobility
mobility_edit_users.html
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
{% from "_formhelpers.html" import render_field %}
{% include 'flash.html' %}
<div class="well">
<form class="form-horizontal" action="" method="post" name="edit">
<div class="control-group">
<input class="btn btn-primary" type="submit" name="submit" value="SelectUser">
<input class="btn btn-primary" type="submit" name="submit" value="Update">
</div>
<div class="control-group">
<select name="user">
{% for user in users %}<option value={{ user }}>{{ user }}</option>{% endfor %}
</select>
</div>
<table border="1" cellpadding="5" cellspacing="5" width="100%" style="background color:white">
{% for attr, value in form._fields.iteritems() %}
<tr>
<th>{{ attr }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</table>
</form>
</div>
{% endblock %}