问题描述
在django管理员中,使用django 1.2,我尝试添加一个InlineModelAdmin,以便在对条目进行更改时对保存应用注释。 (一个条目预计每个编辑都有一个ChangeComment)。
In django admin, using django 1.2, i'm trying to add a InlineModelAdmin to apply a comment on save when a change is made to an entry. (An entry is expected to have a "ChangeComment" for every edit).
我不想显示以前的条目,所以我试图强制 ChangeCommentInline 的formset.queryset为空,通过在 ChangeCommentInline 中创建 NoCommentsInlineFormset 并分配表单,但仍返回现有条目。
I don't want to show previous entries, so I am trying to force the ChangeCommentInline's formset.queryset to be empty, by creating NoCommentsInlineFormset and assigning the formset in my ChangeCommentInline, but is still returning existing entries.
注 - 在链接中上面他们使用了 BaseModelFormset ,我使用的是BaseInlineFormset ,我期望可能是这个问题。如果我使用 BaseModelFormset 将BaseInlineFormset 交换出来,我将收到一个关于实例不存在的错误。
Note - In the link above they use BaseModelFormset, I'm using BaseInlineFormset, which I expect may be the issue. If I swap out BaseInlineFormset with BaseModelFormset I get an error about "instance" not existing.
admin.py
class NoCommentsInlineFormset(models.BaseInlineFormset):
def __init__(self, *args, **kwargs):
super(NoCommentsInlineFormset, self).__init__(*args, **kwargs)
self.queryset = ChangeComment.objects.none()
class ChangeCommentInline(admin.StackedInline):
model = ChangeComment
extra = 1
exclude = ("user", )
formset = NoCommentsInlineFormset
def save_model(self, request, obj, form, change):
"""auto-assign logined in user to comment"""
if not change:
obj.user = request.user
obj.save()
class EntryAdmin(admin.ModelAdmin):
inlines = (ChangeCommentInline, )
可以限制ChangeComment en或者是否有更好的方式来处理这个问题?
Can limiting the ChangeComment entries displayed in the Inline be done, or is there a better way to handle this?
推荐答案
正如在评论中提到的benjaoming一样,有必要覆盖 InlineModelAdmin
中的 get_queryset()
方法。最初没有必要重写和附加一个新的formset到 InlineModelAdmin
定义。
As benjaoming mentioned in the comments, it was necessary to override the get_queryset()
method in the InlineModelAdmin
. It was not necessary to override and attach a new formset to the InlineModelAdmin
definition as I initially thought.
这里是最终实现:
class ChangeCommentInline(admin.StackedInline):
"""For allowing logged in user to add change comment"""
model = ChangeComment
extra = 1
exclude = ("user", ) # auto-update user field in save_formset method of parent modeladmin.
def get_queryset(self, request):
"""Alter the queryset to return no existing entries"""
# get the existing query set, then empty it.
qs = super(ChangeCommentInline, self).get_queryset(request)
return qs.none()
这篇关于限制为django admin内联显示的条目的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!