Django Edit Profile View 不保存新的电子邮件值

Django Edit Profile View not saving new email value

我正在(尝试)实现用户在其个人资料页面上编辑和更新其电子邮件地址的功能。端到端执行此操作时我没有收到任何错误,但新电子邮件未保存到数据库中。

一切似乎都在工作,甚至在 edit_profile 函数中重定向到个人资料页面,但 save() 似乎没有工作,用户电子邮件没有更新,当我我被重定向回个人资料页面,电子邮件仍然是当前值。

谢谢!

型号:

class CustomUser(AbstractUser):
email = models.EmailField(_('email address'), unique=True)
is_pro = models.BooleanField(default=False)
is_golfer = models.BooleanField(default=False)

def __str__(self):
    return self.email

表格

class EditProfileForm(forms.Form):
email = forms.EmailField(
    label='', widget=forms.TextInput(attrs={'class': 'form-field'}))

查看

@login_required
def edit_profile(request):
if request.method == "POST":
    form = EditProfileForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data["email"]
        
        user = CustomUser.objects.get(id=request.user.id)
        user.save()
    return redirect("typeA", username=user.username)
else:
    form = EditProfileForm()
return render(request, "registration/edit_profile.html", {'form': form})

网址

urlpatterns = [
path('type_a_signup/', ASignUpView.as_view(), name='a_signup'),
path('type_b_signup/', BSignUpView.as_view(), name='b_signup'),
path('login/', LoginView.as_view(), name='login'),
path('password_reset', PasswordResetView.as_view(), name='password_reset'),
path('typea/<username>/', typeA, name='typeA'),
path('typeb/<username>/', typeB, name='typeB'),
path('login_success/', login_success, name='login_success'),
path('edit_profile/', edit_profile, name='edit_profile'),
]

模板

<div class="container">
<div class="form-container">
    <h2>Edit profile</h2>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <div>
            {{ form.email.label_tag }}
            <input type="text" class="form-control {% if form.email.errors %}is-invalid{% endif %}" id="id_email"
                name="email" value='{{ form.email.value|default:user.email }}'>
            {% if form.email.errors %}
            <div>{{ form.email.errors }}</div>
            {% endif %}
        </div>
        <button type="submit">Submit</button>
    </form>
    <br>
</div>

您从未设置对象的 email 字段。您应该设置为:

@login_required
def edit_profile(request):
if request.method == "POST":
    form = EditProfileForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data["email"]
        user = request.user
        user<strong>.email = email</strong>  # 🖘 set the email field
        user.save()
        return redirect("typeA", username=user.username)
else:
    form = EditProfileForm()
return render(request, "registration/edit_profile.html", {'form': form})

您应该只在表单成功时重定向。如果不是,Django 将重新呈现 带有错误的表单。