Django管理员。编辑用户并保留密码不变

时间:2019-01-21 12:00:21

标签: django passwords admin

我有自己的自定义用户模型:

class RemoteUser(AbstractUser):

    class Meta:
        verbose_name= 'MyUser'
        verbose_name_plural = 'MyUsers'

    # Custom fields here...

如何设置用户管理表单以编辑隐藏密码的用户详细信息?

class RemoteUserForm(UserCreationForm):
    # What do I put here?

即使我从字段中排除了password,它仍然会给我KeyError 'password1'

1 个答案:

答案 0 :(得分:0)

使用ModelForm,使用起来非常简单。您可以在要编辑的字段中指定要编辑的用户对象的表单类。在视图中使用此表单可以保存输入数据,并在模板中使用上下文来完成循环。

Forms.py     从django.contrib.auth.models导入用户

class EditUserForm(forms.ModelForm):
class Meta:
    model = User
    fields = {'username'}

Views.py

def update_userprofile(request, pk):
    user = User.objects.get(pk=pk)
    user_form = EditUserForm(instance=user)
    if request.user.id == user.id:
        if request.method == "POST":
            user_form = EditUserForm(request.POST, instance=user)
            if user_form.is_valid():
                created_user = user_form.save(commit=False)
                return redirect('someview') #wherever you want

        return render(request, "app_name/update_userprofile.html", {
            "noodle": pk,
            "noodle_form": user_form,}
    else:
        raise PermissionDenied

Update_userprofile.html

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