簡體   English   中英

在Django中覆蓋UserChangeForm

[英]Overriding UserChangeForm in django

由於我不需要編輯表單中的所有字段,因此我一直在尋找一種從Userchangeform中排除某些字段的方法,並且我發現覆蓋表單是可行的

表格

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM