在我的 django ModelAdmin 中,我想根据当前用户组过滤外键选择,并且我想以添加和更改形式实现它。我通过使用以下代码在添加视图中实现了它。
添加视图
def add_view(self, request, form_url = '', extra_context = None):
service_sector = common.getServiceSector(request.user)
ModelForm = self.get_form(request)
if request.POST:
form = ModelForm(request.POST, request.FILES)
else:
form = ModelForm()
if service_sector:
qs = form['member'].field.queryset
qs = qs.filter(service_sector = service_sector)
form['member'].field.queryset = qs
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
self.prepopulated_fields, self.get_readonly_fields(request),
model_admin=self)
context = {
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'show_delete': False,
'root_path': self.admin_site.root_path,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url=form_url, add=True)
在这里它工作正常。在这个模型中,我有一个独特的字段电子邮件,这导致了 change_view 中的问题。我在下面给出了我的 change_view 代码。
更改视图
def change_view(self, request, object_id, form_url = '', extra_context = None):
qs = self.model._default_manager.get_query_set()
service_sector = common.getServiceSector(request.user)
bene_object = Beneficiary.objects.get(pk=object_id)
ModelForm = self.get_form(request, bene_object)
if request.POST:
form = ModelForm(request.POST, request.FILES)
else:
form = ModelForm(instance=bene_object)
if service_sector:
qs = form['member'].field.queryset
qs = qs.filter(service_sector = service_sector)
form['member'].field.queryset = qs
adminForm = helpers.AdminForm(form, list(self.get_fieldsets(request)),
self.prepopulated_fields, self.get_readonly_fields(request),
model_admin=self)
context = {
'adminform': adminForm,
'is_popup': "_popup" in request.REQUEST,
'show_delete': False,
'root_path': self.admin_site.root_path,
}
context.update(extra_context or {})
return self.render_change_form(request, context, form_url = form_url, change = True)
即使我change = True
在我的 change_view 返回中给出了,它也试图将对象保存为新对象。所以我收到一个错误Email already exists
,因为电子邮件字段是唯一值字段。或者是否可以使用正常的 change_view 返回,如下所示:
return super(ModelAdmin, self).change_view(request, form_url, extra_context)
如果是这样,我该如何过滤外键选择。或者如何使用render_change_form
来实现这一点?提前致谢。