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),
syncdband so on.create a
Merchantat django admin. you can see log:u'Merchant'FalseTrueenter 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.
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/6c880992-08f0-477d-a8dc-3b592695f49c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment