2

The problem is I have a model called Gift. And it has a boolean field 'giftbought' that I want to hide in admin interface when the object is being created and show it when it is being updated.

I tryed making a form, overriding init method like:

class GiftForm(forms.ModelForm):
    giftbought = forms.BooleanField(label=u"Bought?", required=False)

    class Meta:
        model = Gift

    def __init__(self, *args, **kwargs):
        super(GiftForm, self).__init__(*args, **kwargs)
        if not self.instance.pk:
            del self.fields['giftbought']

But it doesn't work for admin, like it is being said in: Remove fields from ModelForm

I thing I needed to make a class ModelAdmin, overriding get_form method, but I don't know how to check if I is_instance or not...

It would be something like:

class GiftAdmin(admin.ModelAdmin):
    model = Gift

    def get_form(self, request, obj=None, **kwargs):
        # that IF doesnt work!!!
        if not self.instance.pk:
            self.exclude = ('giftbought',)
        return super(GiftAdmin, self).get_form(request, obj=None, **kwargs)

admin.site.register(Gift, GiftAdmin)

Any hint?

Community
  • 1
  • 1
staticdev
  • 2,950
  • 8
  • 42
  • 66

1 Answers1

0

Definitely your best bet is ModelAdmin. I think you got it right except for the if test.

You should be able to do it like this:

class GiftAdmin(admin.ModelAdmin):
    model = Gift

    def get_form(self, request, obj=None, **kwargs):
        self.exclude = []
        # self.instance.pk should be None if the object hasn't yet been persisted
        if obj is None:
            self.exclude.append('giftbought')
        return super(GiftAdmin, self).get_form(request, obj, **kwargs)

admin.site.register(Gift, GiftAdmin)

Notice there are minor changes to the method code. You should check the docs, I'm sure you'll find everything you need there.

Hope this helps!

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73