unknown
unknown

Reputation: 251

Django ModelForm: Exclude a field which is not in Model

I am having hard time debugging this. I want to exclude confirm_password of RegModelForm in an extended modelform UpdateRegModelForm. I have tried to use exclude in the Meta class of UpdateRegModelForm but it seems to show confirm_password while rendering UpdateRegModelForm anyways. Not sure how to move forward.

class RegModelForm(forms.ModelForm):

    org_admin_email = forms.CharField(
        label='If you know who should be the Admin, please add their email address below.'
              ' We\'ll send them an email inviting them to join the platform as the organization admin.',
        required=False,
        widget=forms.EmailInput(attrs=({'placeholder': 'Email'}))
    )
    organization_name = forms.CharField(
        max_length=255,
        label='Organization Name',
        widget=forms.TextInput(
            attrs={'placeholder': 'Organization Name'}
        )
    )

    confirm_password = forms.CharField(
        label='Confirm Password', widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'})
    )

    class Meta:
        model = ExtendedProfile

        fields = (
            'confirm_password', 'first_name', 'last_name',
            'organization_name', 'is_currently_employed', 'is_poc', 'org_admin_email',
        )

        labels = {
            'is_currently_employed': "Check here if you're currently not employed.",
            'is_poc': 'Are you the Admin of your organization?'
        }

        widgets = {
            'first_name': forms.TextInput(attrs={'placeholder': 'First Name'}),
            'last_name': forms.TextInput(attrs={'placeholder': 'Last Name'}),
            'is_poc': forms.RadioSelect()
        }


class UpdateRegModelForm(RegModelForm):
    class Meta(RegModelForm.Meta):
        exclude = ('confirm_password',)

Upvotes: 2

Views: 1662

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

The fields and exclude attributes are only relevant for fields that are created from the model. Since you've specified confirm_password directly in the form itself, that will always be present.

The way to remove it is to delete it from the fields dictionary of the form. You can do this in the __init__ method:

class UpdateRegModelForm(RegModelForm):
    def __init__(self, *args, **kwargs):
        super(UpdateRegModelForm, self).__init__(*args, **kwargs)
        self.fields.pop('confirm_password')

You don't need to define Meta in this subclass at all.

Upvotes: 2

Related Questions