django - admin model assign value to limit_choices_to from another field inside the model

时间:2017-06-14 10:27:20

标签: python django django-models django-admin limit-choices-to

I have extended the admin model, so for each staff member i can assign other customers only if they are in the same group.

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)     
    is_manager = models.BooleanField(default=False)
    group_account = models.CharField(max_length=3,blank=True,null=True)
    clients_assigned = models.ManyToManyField(User, limit_choices_to = Q(groups__groupaccount__group_account=group_account),blank=True,null=True,related_name='+')

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    verbose_name = "User extra"
    verbose_name_plural = "extra"
    filter_horizontal = ('clients_assigned', )
def save_model(self, request, obj, form, change):
    return super().save_model(request, obj, form, change)

class UserAdmin(BaseUserAdmin):
inlines = [UserProfileInline, ]

def get_form(self, request, obj=None, **kwargs):
    #permissions reduce for regular staff 
     if (not request.user.is_superuser):
         self.exclude = ("app")
         self.exclude = ("user_permissions")
         ## Dynamically overriding
         #self.fieldsets[2][1]["fields"] = ('is_active', 'is_staff','is_superuser','groups')
         self.fieldsets[2][1]["fields"] = ('is_active', 'is_staff')
     form = super(UserAdmin,self).get_form(request, obj, **kwargs)
     return form

and extended the group admin model

class GroupAccount(models.Model):
group_account = models.CharField(,max_length=3,blank=True,null=True)
group = models.OneToOneField(Group,blank=True,null=True)
def save(self, *args, **kwargs):
    super(GroupAccount, self).save(*args, **kwargs)

what im trying to do is simply to limit the client list for each manager-user by his and their group indicator(group_account field), means the available client list are those whom have the same specific group as himself, such as '555'

when the group_account = '555' in the DB the result of groups__groupaccount__group_account=group_account are empty
but if i change it Hardcoded to: groups__groupaccount__group_account='555' its return the relevant result.
is that possible and/or what the alternative?

django 1.9
thanks for the help

1 个答案:

答案 0 :(得分:0)

您应该自定义StackInline的formfield_for_foreignkey方法

class UserProfileInline(admin.StackedInline):
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(UserProfileInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
        if db_field.name == 'clients_assigned':
            u = request.user
            if not u.is_superuser:
                field.queryset = field.queryset.filter(groups__in=u.groups.all())
        return field