Unable to get multiple value in a django model

I am trying to get multiple values for a single label and that label will get two input values. I have added it successfully in the Django admin but when I send a request it gives me a string instead of an array. I have tried the code below. I hope that helps to get the solution.

model.py

class Product(models.Model):
    secondary_author = models.JSONField(blank=True, null=True)

My admin.py

class TwoValuesWidget(forms.MultiWidget):
    def __init__(self, attrs=None):
        widgets = [
            forms.TextInput(attrs={'placeholder': 'Value 1'}),
            forms.TextInput(attrs={'placeholder': 'Value 2'})
        ]
        super().__init__(widgets, attrs)

    def decompress(self, value):
        # Ensure the value is properly decompressed
        if isinstance(value, list) and len(value) == 2:
            return value  # If valid list with two values, return it
        elif isinstance(value, str) and value.startswith('[') and value.endswith(']'):
            # If value is a stringified list, convert to list
            import ast
            return ast.literal_eval(value)
        return ['', '']  # Default to two empty fields if no valid value
    
class MyModelForm(forms.ModelForm):
    secondary_author = forms.CharField(widget=TwoValuesWidget(), label="Secondary Author")

    class Meta:
        model = Product
        fields = '__all__'

    def clean_secondary_author(self):
        values = self.cleaned_data['secondary_author']
        print(values)
        return values
    class ProductAdmin(admin.ModelAdmin):
    form = MyModelForm
    
    def save_model(self, request, obj, form, change):
        obj.secondary_author = form.cleaned_data.get('secondary_author', [])
        super().save_model(request, obj, form, change)
    admin.site.register(Product,ProductAdmin)
    ```
Back to Top