简体   繁体   中英

Overriding UserChangeForm in django

Due to the fact that i don't need to edit all the fields in my form i ve searched for a way to exclude some fields from Userchangeform and i found out that overriding the forms works

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

the problem is that i need to delete that message after the email input 从表单中删除黄色消息

Any ideas?

You don't even need to use the UserChangeForm in this case. See the source of the class:

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% of the extra code is related to the password you don't want, and some for permissions and username. So for your needs just extending ModelForm is enough.

from django.contrib.auth.models import User
from django.forms import ModelForm

class UserChangeForm(ModelForm):

    class Meta:
        model = User
        fields = ('email',)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM