Luiz Carvalho
Luiz Carvalho

Reputation: 1419

Add extra Fields to Django to Django Auth Groups

How add a new field in Group Model of the Django? To use something like

from django.contrib.auth.models import Group
g = Group.objects.get(pk=1)
g.extra_field = "something"
g.save()

it's posssible?

EDIT:

I need a persistent extra field.

Upvotes: 9

Views: 3376

Answers (3)

Ankit
Ankit

Reputation: 51

There's one cleaner way to achieve this if you already use a custom user model Docs here.

You can use the django-group-model package to substitute your own Group model with the extra fields. Here's a short summary on how to do it. Please check the package docs, it goes through the process in detail.

First install the package using pip install django-group-model.

Create a custom group model with the additional fields.

from django_group_model.models import AbstractGroup


class Group(AbstractGroup):
    extra_field = models.CharField(max_length=50, null=True, blank=True)

Set the AUTH_GROUP_MODEL setting.

AUTH_GROUP_MODEL = 'myapp.Group' # Make sure to replace 'myapp' with the appropiate app

Use the new group model with your User model


class User(AbstractUser, ...):
    ...
    groups = models.ManyToManyField(
        'myapp.Group',
        blank=True,
        related_name="user_set",
        related_query_name="user",
    )
    ...

You could also rename the Group model(see docs).

Upvotes: 0

Sankalp
Sankalp

Reputation: 1288

I had the same problem. I wanted to add an extra field in Groups. It worked for me - Monkey patching

Upvotes: 2

Hedde van der Heide
Hedde van der Heide

Reputation: 22459

This isn't in the documentation but fine to use (pre to have a basic understanding of monkey patching), in your models.py or init add:

from django.contrib.auth.models import Group

Group.add_to_class('foo', bar)

Where bar can be any python object (or method), e.g.

def bar(self):
    return self.attr * 2

or using a field mapping:

Group.add_to_class('foo', models.RegexField(r'^hello$'))

Upvotes: 11

Related Questions