I want create a user with custom group in django admin. so I write below code:
from django.contrib.auth.models import User as AuthUser
from django.contrib.auth.models import Group
# These groups have already been created while project start.
class TestGroup(object):
Admin = 'Admin'
Merchant = 'Merchant'
User = 'User'
class Merchant(AuthUser):
def save(self, **kwargs):
super(Merchant, self).save(**kwargs)
for group in Group.objects.all():
print group.name
# way 1
if not self.groups.filter(name=TestGroup.Merchant).exists():
print self.groups.filter(name=TestGroup.Merchant).exists()
g = Group.objects.get(name=TestGroup.Merchant)
g.user_set.add(self)
print self.groups.filter(name=TestGroup.Merchant).exists()
# way 2
if not self.groups.filter(name=TestGroup.Merchant).exists():
g = Group.objects.get(name=TestGroup.Merchant)
self.groups.add(g)
# way 3
if not self.groups.filter(name=TestGroup.Merchant).exists():
g = Group.objects.get(name=TestGroup.Merchant)
self.groups.add(g)
self.save()I have tried three ways to add a group to a user.But none of them could work.
For Test:
You can test by following this steps:
create a group named 'Merchant' at django admin
add my code (add print in way 1 to test), syncdb and so on.
create a Merchant at django admin. you can see log:
u'Merchant'FalseTrue
enter the merchant you just created, you can see, the group merchant is not selected(means this user do not beyond to this group).
click save again, you would still see
u'Merchant'FalseTrue
add group to merchant fail, very strange.