Django:如何从特定用户的管理表单中删除字段?

时间:2011-06-07 20:51:33

标签: django forms django-admin

我的管理员看起来像这样(没有排除变量):

class MovieAdmin(models.ModelAdmin)
    fields = ('name', 'slug', 'imdb_link', 'start', 'finish', 'added_by')
    list_display = ('name', 'finish', 'added_by')
    list_filter = ('finish',)
    ordering = ('-finish',)
    prepopulated_fields = {'slug': ('name',)}

    form = MovieAdminForm

    def get_form(self, request, obj=None, **kwargs):
        form = super(MovieAdmin, self).get_form(request, obj, **kwargs)
        form.current_user = request.user
        return form

admin.site.register(Movie, MovieAdmin)

表格:

class MovieAdminForm(forms.ModelForm):

    class Meta:
        model = Movie

    def save(self, commit=False):
        instance = super(MovieAdminForm, self).save(commit=commit)
        if not instance.pk and not self.current_user.is_superuser:
            if not self.current_user.profile.is_manager:
                instance.added_by = self.current_user.profile
        instance.save()
        return instance

我正在尝试删除用户的added_by字段,因为我更愿意从会话中填充该字段。我尝试过以下方法:

然而,每一个我得到:KeyError while rendering: Key 'added_by' not found in Form。我似乎需要在表单呈现过程中更早地删除该字段,但我仍然坚持要做到这一点。

那么如何为普通用户排除added_by字段?

1 个答案:

答案 0 :(得分:14)

评估list_display时,您可能会收到该错误。您无法显示已排除的字段。删除了added_by的版本也需要相应的list_display。

def get_form(self, request, obj=None, **kwargs):
    current_user = request.user
    if not current_user.profile.is_manager:
        self.exclude = ('added_by',)
        self.list_display = ('name', 'finish')
    form = super(MovieAdmin, self).get_form(request, obj, **kwargs)
    form.current_user = current_user
    return form