由于我不需要编辑表单中的所有字段,因此我寻求一种从Userchangeform中排除某些字段的方法,并且发现覆盖表单是可行的
forms.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
class UserChangeForm(UserChangeForm):
class Meta:
model = User
fields = ('email',)
有什么想法吗?
答案 0 :(得分:1)
在这种情况下,您甚至不需要使用UserChangeForm
。请参阅该类的源代码:
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField(
label=_("Password"),
help_text=_(
"Raw passwords are not stored, so there is no way to see this "
"user's password, but you can change the password using "
"<a href=\"{}\">this form</a>."
),
)
class Meta:
model = User
fields = '__all__'
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
password = self.fields.get('password')
if password:
password.help_text = password.help_text.format('../password/')
user_permissions = self.fields.get('user_permissions')
if user_permissions:
user_permissions.queryset = user_permissions.queryset.select_related('content_type')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
90%的额外代码与您不需要的密码有关,其中一些与权限和用户名有关。因此,对于您的需求,只需扩展ModelForm
就可以了。
from django.contrib.auth.models import User
from django.forms import ModelForm
class UserChangeForm(ModelForm):
class Meta:
model = User
fields = ('email',)