我现在正在提示
peewee.IntegrityError:重复的键值违反了唯一约束
每当我尝试将用户详细信息从用户名“ testing”更新为“ testing2”时。
这是用户。py
class User(UserMixin, BaseModel):
username = CharField(unique=True, null=False)
email = CharField(unique=True, null=False)
password = CharField(unique=False, null=False)
这是views.py
@users_blueprint.route('/profile', methods=['POST'])
@login_required
def edit_profile():
# check whether both email and username has been taken, if not update the specific profile
form = UpdateDetailsForm()
if check_password_hash(current_user.password, form.data['password']):
if current_user.username != form.data['username']:
updated_user = User.update(username=form.data['username']).where(User == current_user)
updated_user.execute()
if current_user.email != form.data['email']:
updated_user = User.update(email=form.data['email']).where(User == current_user)
updated_user.execute()
if form.data['password'] != form.data['new_password']:
# updated_user = User.update(password=generate_password_hash(new_password)).where(User == current_user)
updated_user = User.update(password=generate_password_hash(form.data['new_password'])).where(User == current_user)
updated_user.execute()
flash("Profile successfully updated", "success")
return redirect(url_for('users.view_profile'))
else:
flash("Kindly ensure that the initial password matches", "danger")
return redirect(url_for('users.view_profile'))
return redirect(url_for('users.view_profile'))
这是profile.html
{% extends "_layout.html" %}
{% block content %}
<div class="container">
<div class="content-section">
<form method="POST" action="{{ url_for('users.edit_profile') }}" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.hidden_tag() }}
{% for field in form if field.name != "csrf_token" %}
<div class="form-group">
{% if field.name != "btn" %}
{{ field.label(class="form-control-label form-control-lg") }}
{% endif %}
{% if field.name != "btn" %}
{% if field.name == "username" %}
{{ field(class="form-control", value=current_user.username) }}
{% elif field.name == "email" %}
{{ field(class="form-control", value=current_user.email) }}
{% elif field.name == "password" %}
{{ field(class="form-control", value=current_user.password) }}
{% elif field.name == "new_password" %}
{{ field(class="form-control", value=current_user.password) }}
{% endif %}
{% else %}
{{ field(class="btn btn-outline-info") }}
{% endif %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
</div>
{% endfor %}
</form>
</div>
</div>
{% endblock %}
这是表格。py
class UpdateDetailsForm(FlaskForm):
username = StringField(
'Username',
validators=[
DataRequired(),
Length(min=5, max=20)
]
)
email = StringField(
'Email',
validators=[
DataRequired(),
Email()
]
)
password = PasswordField(
'Password',
validators=[
DataRequired(),
Length(min=8, max=20)
]
)
new_password = PasswordField(
'New Password',
validators=[
DataRequired(),
Length(min=8, max=20)
]
)
btn = SubmitField('Update Profile')
答案 0 :(得分:1)
尝试更改where子句:
.where(User.id == current_user.id)