Login

Add custom fields to the built-in Group model

Author:
jmoppel
Posted:
December 19, 2022
Language:
Python
Version:
3.2
Score:
1 (after 1 ratings)

Add fields and extend Django's built-in Group model using a OneToOneField (i.e. a profile model). In this example, we add a UUIDField. Whenever a new group is created, we automatically (via signals) create a corresponding Role record referencing the newly created group. Whenever a Group is deleted, the corresponding Role is deleted as well.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from uuid import uuid4
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Role(models.Model):
    """Extension of Django's built-in Group model

    Adds a UUID field to Django's built-in Group model.
    """

    uuid = models.UUIDField(
        auto_created=True,
        default=uuid4,
        editable=False,
        help_text="object ID",
        primary_key=True,
        unique=True,
    )
    group = models.OneToOneField(Group, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.group.name}"


@receiver(post_save, sender=Group)
def create_role(sender, instance, created, **kwargs):
    if created:
        Role.objects.create(group=instance)

More like this

  1. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 4 months, 4 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 5 months, 1 week ago
  3. Browser-native date input field by kytta 6 months, 3 weeks ago
  4. Generate and render HTML Table by LLyaudet 7 months ago
  5. My firs Snippets by GutemaG 7 months, 1 week ago

Comments

Please login first before commenting.