python - 在 django 中覆盖 UserChangeForm
问题描述
由于我不需要编辑表单中的所有字段,我已经搜索了一种从 Userchangeform 中排除某些字段的方法,我发现覆盖表单有效
表格.py
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
class UserChangeForm(UserChangeForm):
class Meta:
model = User
fields = ('email',)
有任何想法吗?
解决方案
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',)
推荐阅读
- javascript - Laravel 与 PHP 助手的混合
- c++ - 在成对的向量中搜索
- php - 将语音转换为文本或值 laravel
- python - 在 Python 中为 Selenium 多会话打开脚本添加代理支持
- java - java.lang.VerifyError:ClientProxy 覆盖最终方法
- environment-variables - 如何使用根目录中的 .env 文件?
- r - R: bench::mark 不返回最大值和平均值
- java - java如何在jar包中导入一个类
- javascript - 使用 webpack 4 去混淆 javascript
- soap - Sabre SOAP - wsse:Security - 未绑定