5

My admin looks like this (with no exclude variable):

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)

The form:

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

I'm trying to remove the added_by field for users since I'd prefer to populate that from the session. I've tried methods from the following:

However with each one I get: KeyError while rendering: Key 'added_by' not found in Form. It seems I need to remove the field earlier in the form rendering process but I'm stuck on where to do this.

So how can I exclude the added_by field for normal users?

Community
  • 1
  • 1
ghickman
  • 5,893
  • 9
  • 42
  • 51

1 Answers1

15

You're probably getting that error when list_display is evaluated. You can't show a field that's excluded. The version with added_by removed also needs a corresponding 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
Danny W. Adair
  • 12,498
  • 4
  • 43
  • 49
  • and yes, you set exclude and list_display on the ModelAdmin _before_ instantiating its form – Danny W. Adair Jun 08 '11 at 00:42
  • Hmm, on second thought - thanks for the vote :-) - list_display isn't used by the form, it's used by the change list. It was just the order that was the problem. – Danny W. Adair Jun 09 '11 at 01:29