代码之家  ›  专栏  ›  技术社区  ›  Az Emna

在django中重写UserChangeForm

  •  -1
  • Az Emna  · 技术社区  · 6 年前

    由于我不需要编辑表单中的所有字段,所以我搜索了一种从Userchangeform中排除某些字段的方法,发现重写表单是可行的

     from django.contrib.auth.models import User
    from django.contrib.auth.forms import UserChangeForm
    
    class UserChangeForm(UserChangeForm):
    
        class Meta:
            model = User
            fields = ('email',)
    

    问题是,我需要删除邮件输入后的消息 delete the yellow message from the form

    1 回复  |  直到 6 年前
        1
  •  1
  •   Anonymous    6 年前

    你甚至不需要使用 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',)