Semb
Semb

Reputation: 166

How to rename a model field from default Django model?

I would like to rename all the Groups field in Django admin as Roles field. But there are still some parts that didn't changed.

I have successfully renamed Groups into Roles using this code (models.py):

class Role(Group):
    class Meta:
        proxy = True
        app_label = 'auth'
        verbose_name = _('role')
        verbose_name_plural = _('roles')

    def __str__(self):
        return self.name

but then a field in the Users still has the name 'Groups' in it. Please see screenshot attached.

I know it has something to do with the PermissionsMixin in django.contrib.auth.models which contains the ManyToManyField named groups that is being called in the UserAdmin.

class PermissionsMixin(models.Model):
    ...
    groups = models.ManyToManyField(
        Group,
        verbose_name=_('groups'),
        blank=True,
        help_text=_(
            'The groups this user belongs to. A user will get all permissions '
            'granted to each of their groups.'
        ),
        related_name="user_set",
        related_query_name="user",
    )
    ...

I would like to know how to rename this model field.

Edit: Here is the code for the UserAdmin:

    class UserAdmin(BaseUserAdmin):
        form = UserAdminChangeForm
        add_form = UserAdminCreationForm

        list_display = ('username',)
        fieldsets = (
            (None, {'fields': ('username', 'password',)}),
            (None, {'fields': ('groups',)}),
        )
        add_fieldsets = (
            (None, {
                'classes': ('wide',),
                'fields': ('username', 'password1', 'password2')}
            ),
        )
        filter_horizontal = ('groups',)

Upvotes: 3

Views: 1780

Answers (1)

user2390182
user2390182

Reputation: 73498

You almost certainly do not want to rename the model field, but simply change the label in the admin. You can achieve that by customizing the admin form. Something along the following lines should do the trick:

class UserAdmin(BaseUserAdmin):
    # ...
    def get_form(self, request, obj=None, change=False, **kwargs):
        kwargs['labels'] = {'groups': 'roles'}
        return super().get_form(request, obj=obj, change=change, **kwargs)

Upvotes: 2

Related Questions