Ross Symonds
Ross Symonds

Reputation: 710

Hiding Email Address On UserUpdateForm

I want the user to be able to update their username but not email address. In example 3 despite the fact I do not include the field email in my code, the field still appears when I run the site. Admittedly the text box is blank whereas in example 1 and 2 it is populated.

How can I stop the email text box appearing? Or can I lock it so the user cannot enter a new value?

Example 1 enter image description here

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email']

Example 2 enter image description here

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['email']

Example 3

enter image description here

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username']

Upvotes: 0

Views: 233

Answers (2)

Charnel
Charnel

Reputation: 4432

Since you need all other fields except email (or at least you mentioned only email as the one you'd like to hide), perhaps you can use then exclude attribute:

from django.forms import ModelForm

class UserUpdateForm(ModelForm):

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

For more details you can read in this doc.

Also, alternative way to go is to disable field (not checked):

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField(disabled=True)

    class Meta:
        model = User
        fields = ['username', 'email']

Passing disabled=True should still render the field but unable it edition by user.

Upvotes: 0

Iqbal Hussain
Iqbal Hussain

Reputation: 1105

from django.forms import ModelForm

class UserUpdateForm(ModelForm):
    #email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username']

Upvotes: 2

Related Questions