这很简单,适用于Django 1.4:
class ClientAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ClientAdminForm, self).__init__(*args, **kwargs)
# access object through self.instance...
self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)
class ClientAdmin(admin.ModelAdmin):
form = ClientAdminForm
....
你不需要在表单类中指定这个,但可以直接在ModelAdmin中执行,因为Django已经在ModelAdmin中包含了这个内置方法(来自文档):
ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to
override the default formfield for a foreign keys field. For example,
to return a subset of objects for this foreign key field based on the
user:'''
class MyModelAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "car":
kwargs["queryset"] = Car.objects.filter(owner=request.user)
return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
一种更好的实现方法(例如创建用户可以访问的前端管理界面)是将ModelAdmin子类化,然后修改下面的方法。最终的结果是用户界面只显示与他们相关的内容,同时允许你(超级用户)看到一切。
我重写了四个方法,前两个方法使用户无法删除任何东西,它还从管理站点删除按钮。
第三个覆盖过滤任何包含引用的查询(在示例“user”或“porcupine”中(仅作为示例)。
最后一个覆盖过滤模型中的任何外键字段,以过滤与基本查询集相同的可用选项。
通过这种方式,您可以提供一个易于管理的前端管理站点,允许用户摆弄自己的对象,并且您不必记得输入我们上面谈到的特定ModelAdmin过滤器。
class FrontEndAdmin(models.ModelAdmin):
def __init__(self, model, admin_site):
self.model = model
self.opts = model._meta
self.admin_site = admin_site
super(FrontEndAdmin, self).__init__(model, admin_site)
删除“删除”按钮:
def get_actions(self, request):
actions = super(FrontEndAdmin, self).get_actions(request)
if 'delete_selected' in actions:
del actions['delete_selected']
return actions
禁止删除权限
def has_delete_permission(self, request, obj=None):
return False
过滤可以在管理站点上查看的对象:
def get_queryset(self, request):
if request.user.is_superuser:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
return qs
else:
try:
qs = self.model.objects.all()
except AttributeError:
qs = self.model._default_manager.get_queryset()
if hasattr(self.model, ‘user’):
return qs.filter(user=request.user)
if hasattr(self.model, ‘porcupine’):
return qs.filter(porcupine=request.user.porcupine)
else:
return qs
过滤管理站点上所有外键字段的选择:
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if request.employee.is_superuser:
return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
else:
if hasattr(db_field.rel.to, 'user'):
kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
if hasattr(db_field.rel.to, 'porcupine'):
kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)