Snowflake
Snowflake

Reputation: 301

Django-Admin: how to use one field for both inlinemodel and model

Hello i am working in django admin panel, i am making 2 models

workflow, and workflow stages, both has filed company

workflow is inline inside of workflow

my question is how to make all of the workflow stages uses the same company field up in the workflow.

class WorkflowStageInline(admin.TabularInline):
    model = WorkflowStage
    extra = 7


class WorkflowAdmin(admin.ModelAdmin):
    inlines = [WorkflowStageInline, ]
    list_display = ('id', 'company', 'is_template')
    list_display_links = ('id', 'company')

enter image description here

Upvotes: 1

Views: 233

Answers (1)

dirkgroten
dirkgroten

Reputation: 20702

Add these two methods to your WorkflowStageInline class:

def get_formset(self, request, obj=None, **kwargs):
    self.parent_obj = obj
    return super().get_formset(request, obj, **kwargs)

def formfield_for_dbfield(self, db_field, request, **kwargs):
    field = super().formfield_for_dbfield(db_field, request, **kwargs)
    if db_field.name == 'company':
        field.initial = self.parent_obj.company if self.parent_obj else None
    return field

get_formset() adds the parent object to each inline instance. formfield_for_dbfield() uses that parent object to populate the initial value of the company field.

Upvotes: 2

Related Questions