Making a field Read-Only in Django

688 views
Skip to first unread message

Frankline

unread,
Nov 17, 2014, 1:48:44 AM11/17/14
to django...@googlegroups.com
Hi all,

I'm running Django 1.7 and Python 3.4. I'm trying to make the username field of my custom model to be read-only. I think this is usually set in the form. Below is what I currently have in my forms.py

class AuthUserChangeForm(UserChangeForm):
    """
    A form for updating users. Includes all the fields on the user, but 
    replaces the password field with admin's password hash display field.
    """
    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=\"password/\">
                                         this form</a>""")

    class Meta:
        model = AuthUser
        fields = ('username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser', 'user_permissions')
        widgets = {
            'username': TextInput( attrs={'readonly':'readonly'} ),
            'email': TextInput(),
        }

    def clean_username(self):
        # Regardless of what the user provides, reset field to initial value
        # Not appropriate to change usernames once set.
        return self.initial["username"]
        
    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"]


What I'm I missing here?

Patrick Beeson

unread,
Nov 17, 2014, 8:52:24 AM11/17/14
to django...@googlegroups.com
I believe you can set this via a built-in widget's attrs:

somefield = forms.CharField(
    widget=forms.TextInput(attrs={'readonly':'readonly'})
)
Reply all
Reply to author
Forward
0 new messages