Can not add a group to a custom auth user

225 views
Skip to first unread message

Ikaros andi

unread,
Aug 26, 2014, 5:05:33 AM8/26/14
to django...@googlegroups.com

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:

  1. create a group named 'Merchant' at django admin

  2. add my code (add print in way 1 to test), syncdb and so on.

  3. create a Merchant at django admin. you can see log:

    u'Merchant'
    False
    True

  4. enter the merchant you just created, you can see, the group merchant is not selected(means this user do not beyond to this group).

  5. click save again, you would still see

    u'Merchant'
    False
    True

add group to merchant fail, very strange.

Collin Anderson

unread,
Aug 27, 2014, 10:08:15 AM8/27/14
to django...@googlegroups.com
i assume "groups" is an editable field in the admin.

after the admin calls merchant.save(), it then clears out and re-assigns the value of groups based on the data in the input field.

Ikaros andi

unread,
Sep 1, 2014, 2:15:22 AM9/1/14
to django...@googlegroups.com
I debug into save method and find:

ValueError: "<Merchant: m23533>" needs to have a value for field "user" before this many-to-many relationship can be used.

Merchant have already been super saved. I can figure it out

Ikaros andi

unread,
Sep 1, 2014, 2:25:52 AM9/1/14
to django...@googlegroups.com
super(Merchant, self).save(force_insert=True) 

solved the problem!
Reply all
Reply to author
Forward
0 new messages