Reputation: 7386
I am using save_model to add an User to particular Group
def UserAdmin(UserAdmin):
def save_model(self, request, obj, form, change):
adminOb = Group.objects.get(name='Administrator')
adminOb.user_set.add(obj.pk)
adminOb.save()
obj.save()
This code is not adding the obj.pk
to `adminOb' the but when I do this in terminal I am able to save
In terminal I did this
adminOb = Group.objects.get(name='Administrator')
adminOb.user_set.add(44)
adminOb.save()
Note : I use werkzeug debugging tool, via which I can console in browser, I tested in this console, for the console to appear in the browser the page should have some error, so instead of adminOb.save()
I used adminOb.saved()
,then in console I run this adminOb.save()
, Surprisingly this is saving the adminOb
Upvotes: 1
Views: 593
Reputation: 1
def save_model(self, request, obj, form, change):
obj.save()
adminOb = Group.objects.get(name='INDURE USER')
adminOb.user_set.add(obj.pk)
adminOb.save()
Try this because in many to many fields it cannot set a field value until it gets the id of another field. Until the user is not created, it cannot set its group, so first we need to save the object then add modifications or updates. Thus it saves once the object is created in case of many to many fields. Thus this is a transaction problem for many to many fields in Django. And dont forget to exclude groups in "fields".
Upvotes: 0
Reputation: 7386
The mistake I done is I didn't exclude the groups, which made to override Group of an user with the form fields,
fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser'
)}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
Upvotes: 1