Inline formset in Django - removing certain fields

mermer picture mermer · Feb 18, 2009 · Viewed 10.5k times · Source

I need to create an inline formset which

a) excludes some fields from MyModel being displayed altogether

b) displays some some fields MyModel but prevents them from being editable.

I tried using the code below, using values() in order to filter the query set to just those values I wanted returned. However, this failed.

Anybody with any idea?

class PointTransactionFormset(BaseInlineFormSet):
    def get_queryset(self):
        qs = super(PointTransactionFormset, self).get_queryset()
        qs = qs.filter(description="promotion feedback")
        qs = qs.values('description','points_type') # this does not work
        return qs

class PointTransactionInline(admin.TabularInline):
    model = PointTransaction
    #formset = points_formset()
    #formset = inlineformset_factory(UserProfile,PointTransaction)
    formset = PointTransactionFormset

Answer

killerbarney picture killerbarney · Jan 26, 2011

One thing that doesn't seem to be said in the documentation is that you can include a form inside your parameters for model formsets. So, for instance, let's say you have a person modelform, you can use it in a model formset by doing this

PersonFormSet = inlineformset_factory(User, Person, form=PersonForm, extra=6)

This allows you to do all the form validation, excludes, etc on a modelform level and have the factory replicate it.