Django form.isValid()在自定义用户模型中始终返回false

时间:2018-12-07 10:57:03

标签: django django-authentication

this tutorial之后,我在Django中有一个自定义用户模型。但是,当我更新用户时,会收到错误消息“具有此电子邮件地址的用户已存在。”。当我的模型扩展AbstractBaseUser时,这不是由Django本身处理吗?

我的观点:

@login_required
def user_add_edit(request, pk=None):
    user = get_user_model()
    if request.method == 'POST':
        if pk:
            form = UserChangeForm(request.POST)
        else:
            form = UserCreationForm(request.POST)

        if form.is_valid():
            user = form.save(commit=False)
            msg = ''
            if len(user.last_name) > 0:
                user.last_name = user.last_name.title()

            if len(user.first_name) > 0:
                user.first_name = user.first_name.title()

            user.password(user.set_password(request.POST['password2']))
            user.save()

            messages.add_message(request, messages.SUCCESS, 'User  updated with success. %s' % msg)

            data = {'valid': True}
            return JsonResponse(data)
        else:
            data = {'valid': False, 'formMsg': [v for k, v in form.errors.items()]}
            return JsonResponse(data)

    else:
        if pk:
            selected_user = get_object_or_404(user, pk=pk)
            form = UserChangeForm(request.POST or None, instance=selected_user)
        else:
            selected_user = get_user_model()
            form = UserCreationForm(request.POST or None, instance=selected_user, initial={'password1': "", 'password2': "", 'first_name': "", 'last_name': "", 'email': ""})

        return render(request, 'users/add_edit.html', {'form': form, 'selectedUser': selected_user})

1 个答案:

答案 0 :(得分:1)

if request.method == 'POST':
        if pk:
            selected_user = get_object_or_404(user, pk=pk)
            form = UserChangeForm(request.POST,instance=selected_user)

使用此