Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add extra Fields to Django to Django Auth Groups

Tags:

django

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.

like image 359
Luiz Carvalho Avatar asked May 06 '13 21:05

Luiz Carvalho


People also ask

Can you add fields to Django user model?

According to django documentation, you should create a custom user model whenver you start a django project. Because then you will have full control over the fields of the user objects in django, and you can add as many custom fields to the user model as you need and whenever you need.


2 Answers

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$'))
like image 103
Hedde van der Heide Avatar answered Oct 04 '22 09:10

Hedde van der Heide


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

like image 35
Sankalp Avatar answered Oct 04 '22 10:10

Sankalp