Django:使用自定义表单更新用户字段

Django: Update user fields using a custom form

工作人员可以 register/update 用户个人资料。我的注册功能正常,但个人资料更新不正常。

我收到此错误:'int' 对象没有属性“_meta”。

forms.py

from django.contrib.auth.forms import UserCreationForm, UserChangeForm

class RegisterForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False)
    last_name = forms.CharField(max_length=30, required=False)
    Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ]
    group_name = forms.ChoiceField(choices=Group)
    is_active = forms.BooleanField(initial=True, required=False)

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', )


class UpdateForm(UserChangeForm):
    is_active = forms.BooleanField(required=False)
    Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ]
    group_name = forms.ChoiceField(choices=Group)

    class Meta:
        model = User
        fields = ('email', 'is_active', 'group_name', )

views.py

@login_required
@group_required('Staff')
def registerView(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            group = Group.objects.get(name=request.POST.get('group_name'))
            user.groups.add(group)
            return redirect('accounts:users')
    else:
        form = RegisterForm()

    return render(request, 'accounts/register.html', {'form': form})


# Update status of user
@login_required
@group_required('Staff')
def updateUserView(request, id):
    if request.method == 'POST':
        form = UpdateForm(request.POST, instance=id)
        if form.is_valid():
            user = form.save()
            group = Group.objects.get(name=request.POST.get('group_name'))
            user.groups.add(group)
            return redirect('accounts:users')
    else:
        form = UpdateForm(instance=id)

    return render(request, 'accounts/update_user.html', {'form': form})


urls.py

path('users/<int:id>/update', views.updateUserView, name='update'),

我错过了什么?有更简单的方法吗?

你必须给你的 UpdateForm 一个实例,而不仅仅是 ID。

这个:

form = UpdateForm(instance=id)

应该是这样的:

form = UpdateForm(instance=User.objects.get(id=id))