[Solved]-Exclude username or password from UserChangeForm in Django Auth

20👍

For Django v2 just set password to None.

class UserForm(UserChangeForm):
    password = None

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

11👍

You won’t be able to do this if you use UserChangeForm.

See this https://github.com/django/django/blob/master/django/contrib/auth/forms.py.

You will notice that UserChangeForm on this page explicitly defines username and password. These fields are present in variable declared_fields on the form.

exclude and fields only work on fields which are taken from model defined in Meta. If you explicitly define some field i.e declared_fields, they will be present on the form even if they have been excluded using exclude. So, these fields show for you.

To read more on this check __new__ of ModelFormMetaclass at https://github.com/django/django/blob/master/django/forms/models.py

Workaround:

Do not use UserChangeForm and read its code. It doesn’t provide you much. You can write your own form which only extends from ModelForm and set Meta Model as user. Copy the parts from UserChangeForm in your form.

class UserForm(forms.ModelForm):

    class Meta:
        model = User

    def __init__(self, *args, **kwargs):
        #copy any functionality you want form UserChangeForm

    def clean_password(self):
        #copy functionality provided by UserChangeForm 

1👍

i think it may help you …

while iterating over form field in template,write

if for field in UserChangeFormObject:
    {% ifnotequal field.lable password %}
        #process your form field here
    {% endifnotequal%}

Read more here https://docs.djangoproject.com/en/1.6/releases/1.2/

👤Ravi

Leave a comment