How do I extend the Django Group model?

前端 未结 4 1047
Happy的楠姐
Happy的楠姐 2020-12-01 02:12

Is there a way to extend the built-in Django Group object to add additional attributes similar to the way you can extend a user object? With a user object, you can do the fo

4条回答
  •  渐次进展
    2020-12-01 02:39

    For me worked solution based on:

    https://docs.djangoproject.com/pl/1.11/topics/auth/customizing/#extending-user

    Let me explain what I did with Groups extending default model with email alias:

    First of all I created my own django application let name it

    python manage.py startapp auth_custom

    Code section:

    In auth_custom/models.py I created object CustomGroup

    from django.contrib.auth.models import Group
    from django.db import models
    
    class CustomGroup(models.Model):
            """
            Overwrites original Django Group.
            """
            def __str__(self):
                return "{}".format(self.group.name)
    
            group = models.OneToOneField('auth.Group', unique=True)
            email_alias = models.EmailField(max_length=70, blank=True, default="")
    

    In auth_custom/admin.py:

    from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
    from django.contrib.auth.models import Group
    
    
    class GroupInline(admin.StackedInline):
        model = CustomGroup
        can_delete = False
        verbose_name_plural = 'custom groups'
    
    
    class GroupAdmin(BaseGroupAdmin):
        inlines = (GroupInline, )
    
    
    # Re-register GroupAdmin
    admin.site.unregister(Group)
    admin.site.register(Group, GroupAdmin)
    

    After making migrations I have such result in Django Admin view.

    Custom Group in Django Admin

    In order to access this custom field you must type:

    from django.contrib.auth.models import Group
    
    
        group = Group.objects.get(name="Admins")  # example name
    
        email_alias = group.customgroup.email_alias
    

    If any mistakes please notify me, I'll correct this answere.

提交回复
热议问题