更新自定义用户配置文件

Updating custom user profile

在我的网络应用程序中,我需要两个用户,普通网站用户和员工。我正在使用基于 AbstractUser 的自定义用户来实现此目的。

class CustomUser(AbstractUser):
    pass

class Employee(CustomUser):
    user = models.OneToOneField(settings.AUTH_USER_MODEL)
    # other fields

在settings.py我有:

AUTH_USER_MODEL = 'app.CustomUser'

我想为普通网站用户和员工用户提供个人资料页面。

首先,我为普通站点用户创建了一个名为 UserProfileEditForm 的表单:

class UserProfileEditForm(forms.ModelForm):
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=False)
    last_name = forms.CharField(required=False)

    class Meta:
        model = get_user_model()
        fields = ('email', 'first_name', 'last_name')

    def clean_email(self):
        username = self.cleaned_data.get('username')
        email = self.cleaned_data.get('email')

        if email and get_user_model().objects.filter(email=email).exclude(username=username).count():
            raise forms.ValidationError('This email address is already in use. Please supply a different email address.')
        return email

    def save(self, commit=True):
        user = super(UserProfileEditForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

对应视图:

@login_required
def user_profile_edit(request):
    user = get_user_model()
    if request.method == 'POST':
        form = UserProfileEditForm(request.POST, instance=request.user)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            return redirect('user_profile')
    else:
        form = UserProfileEditForm(instance=request.user)
    return render(request, 'user/user_profile_edit.html', {
        'form': form
    })

和表格:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Update Information</button>
</form>

在编辑用户个人资料页面中,我看到电子邮件正确填充到电子邮件字段中。当我点击提交时,我收到一条验证错误消息:

This email address is already in use. Please supply a different email address.

好像更新表单正在尝试创建一个新用户。我该怎么做才能解决这个问题?

额外问题:同样的解决方案是否适用于员工用户的用户个人资料页面?

从 clean_email 方法内的 if 子句中的查询中删除 .exclude(username=username)

由于表单 class UserProfileEditForm 中没有用户名字段,因此从 cleandata 获取用户名是无用的,它将始终是 None

同时将 self.instance.email != email 添加到 if 子句中,以便当前用户可以更新他的个人资料信息。

if email and self.instance.email != email and get_user_model().objects.filter(email=email).count():

更新 2

注销问题是由于您的 user_profile_edit 方法中的以下代码造成的

if form.is_valid():
   user = form.save(commit=False)
   # below line of code deactivating user and hence user got logged out, remove these lines 
   user.is_active = False
   user.save()

将以上代码行更改为

# You have already mentioned a save method inside UserProfileEditForm class
if form.is_valid():
   form.save()