Andrew
Andrew

Reputation: 433

Changing label in auth.User model field

How to change label for User field, e.g. for username? I'm using CustomUser model that inherits AbstractUser, and I want to change label for some fields. I try do next in CustomUser model, but it's not working. Any ideas?

class CustomUser(AbstractUser):
    mobile = models.CharField(max_length=16)
    address = models.CharField(max_length=100)
    def __init__(self, *args, **kwargs):
        super(CustomUser,self).__init__(*args, **kwargs)
        self.username.__setattr__('label', 'Some text')

Upvotes: 0

Views: 848

Answers (1)

aumo
aumo

Reputation: 5554

A Django model's fields are moved to Model._meta at class initialization, since Django 1.8, you can access them using the _meta API.

Also, label is an attribute of form fields, the equivalent for model fields is verbose_name.

This should work an Django 1.8

class CustomUser(AbstractUser):
    mobile = models.CharField(max_length=16)
    address = models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        super(CustomUser,self).__init__(*args, **kwargs)
        self._meta.get_field('username').verbose_name = 'Some text'

Before Django 1.8 you can use self._meta.get_field_by_name('username')[0] instead of self._meta.get_field('username').

Upvotes: 1

Related Questions