Luis Masuelli
Luis Masuelli

Reputation: 12333

Modifying username field in user subclass

How can I modify, in a model subclass, an attribute of a field in a parent class?

This means: I want to create a subclass of djando.contrib.auth.models.AbstractUser and have my custom model with the same fields BUT modifying the username field: I want to change its validators and help_text.

Question: How can I redefine a field in a subclass? The things I must change are not database-related, but model-logic-related, and my intention is to use that model in, at least, a ModelForm.

Upvotes: 0

Views: 75

Answers (1)

knbk
knbk

Reputation: 53669

You can get the field by using the get_field method in the model's meta class:

class User(AbstractUser):
    custom_field = models.BooleanField()
    ...

User._meta.get_field('username').validators = [list of validators,]
User._meta.get_field('username').help_text = "Help text"

Note that this will change the field's settings for all subclasses and superclasses of User as well, as long as they have the field, because the field's metadata is shared across all classes.

Upvotes: 1

Related Questions