Skip to content

Issue with polymorphic_ctype when populating polymorphic inline formsets. #549

@michaelbaisch

Description

@michaelbaisch

When trying to populate a polymorphic inline formset using the django-polymorphic package, I'm encountering a problem with the polymorphic_ctype field.

Context

In the get_context_data method, I populate the formset's initial data using:

ct = ContentType.objects.get_for_model(constraint)
initial[i]['polymorphic_ctype'] = ct

This works for an initial GET request to display the form. However, upon a POST, the formset becomes populated with the POST data where polymorphic_ctype is a string (eg "scheduler | sun separation constraint") and not the expected id, leading to an error:

["Formset row constraint_set-0 has no 'polymorphic_ctype' defined!"]

Expected Behavior

The polymorphic_ctype should be correctly recognized.

Current Behavior

The code expects an instance of ContentType:

model = defaults["initial"]["polymorphic_ctype"].model_class()

However, it also tries to retrieve an id from the POST data, which causes the inconsistency:

ct_id = int(self.data[f"{prefix}-polymorphic_ctype"])

Django version: 4.2.4
django-polymorphic version: 3.1.0
Python version: 3.11.5

Is there a better method to populate the formset? I'm attempting this approach to implement a "Duplication" feature. The intention is for the form to display data from the original Job and its associated constraints. This data has not been saved yet, allowing the user to make any necessary corrections.

 class JobDuplicateView(JobCreateView):
    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)

        cloned_constraints = self.duplicated_constraints
        
        # Prepopulate the formset with the cloned constraints
        initial = [{} for _ in cloned_constraints]
        for i, constraint in enumerate(cloned_constraints):
            constraint_form = data['constraint_formset'].get_form_class(constraint.__class__)()

            ct = ContentType.objects.get_for_model(constraint)
            initial[i]['polymorphic_ctype'] = ct

            for name, field in constraint_form.fields.items():
                if name != "id" and name != "job":
                    initial[i][name] = getattr(constraint, name)

        data['constraint_formset'].initial = initial
        data['constraint_formset'].extra = len(cloned_constraints)

        return data

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions