首页 > 解决方案 > 在 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',)

问题是我需要在输入电子邮件后删除该消息 从表单中删除黄色消息

有任何想法吗?

标签: pythondjango

解决方案


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',)

推荐阅读