1

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

4

2 回答 2

1

我犯的错误是我没有排除组,这些组使用表单字段覆盖用户的组,

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')}),
)
于 2013-07-23T19:46:41.610 回答
0
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()

试试这个,因为在多对多字段中,它无法设置字段值,直到它获取另一个字段的 id。在没有创建用户之前,它不能设置它的组,所以首先我们需要保存对象然后添加修改或更新。因此,在多对多字段的情况下,一旦创建对象,它就会保存。因此,对于 Django 中的多对多字段来说,这是一个事务问题。并且不要忘记排除“字段”中的组。

于 2015-02-12T07:44:44.767 回答