Ersain
Ersain

Reputation: 1520

Adding extra fields to django InlineFormSet

Suppose I have 3 models:
Chess Player
Tournament
Participation

"Participation" is a junction table of two others.

structure

I use the following InlineFormSet in admin panel in order to show some fields from Participation model.

from .models import Participation


class ParticipationInline(admin.TabularInline):
    model = Participation
    formset = ParticipationAdminFormset


class BaseParticipationAdminFormset(BaseInlineFormSet):
    def clean(self):
        # Some code
        # ...

    def _construct_form(self, i, **kwargs):
        # Some code
        # ...


ParticipationAdminFormset = inlineformset_factory(
    Tournament, Participation,
    formset=BaseParticipationAdminFormset,
    fields=("chess_player_id", "tournament_id", "is_active")
)

The Question: How can I include any fields from "Chess_Player" model, e.g. "first_name", into the FormSet above?

Upvotes: 2

Views: 108

Answers (1)

Ersain
Ersain

Reputation: 1520

After a little surfing, I managed to solve the problem: All what I had to do was to add read-only fields and include chess_player attributes:

class ParticipationInline(admin.TabularInline):
    model = Participation
    formset = ParticipationAdminFormset
    readonly_fields = ['chess_player_name']

    def chess_player_name(self, instance):
        return instance.chess_player.first_name

Upvotes: 1

Related Questions