Django Admin. Display not-model field

Is it possible to display non-model field in django admin?

For example, I have the model:

class TestModel(models.Model):
     value = models.DecimalField(max_digits=5, decimal_places=2)

In Django admin I want to display custom fields "coefficient 1", "coefficient 2" that is not a model field, so I do not want to keep its values in the database. This coefficients is going to be used to calculate "value" field of model.

The coefficients are generated using some algorithm. (for example, we have model CoefficientGenerator to keep its names and values).

This fields are dynamically generated, so I can not declare it in model body. But user must have possibility to edit coefficients before save the instance using django admin.

I tried to overwrite method get_fieldsets in ModelAdmin:

class TestModelAdmin(ModelAdmin):
    def get_fieldsets(self, request, obj=None):
        fieldsets = super(ProductAdmin, self).get_fieldsets(request, obj)
        for c in CoefficientGenerator.objects.all():
            fieldsets[0][1]['fields'].append(c.name)
        return fieldsets

And also to overwrite init in my custom admin form:

def __init__():
    ...
    for c in CoefficientGenerator.objects.all():
        field = forms.CharField(required=False, widget=forms.Textarea, label=c.name)
        self.fields[c.name] = field

But it did not worked for me. I got the error: Unknown field(s) (....) specified for TestModel

Thanks.

Upvotes: 1

Views: 1489

Answers (2)

Joeri
Joeri

Reputation: 1

I know this is a very old topic but at least in Django 3.2+ you can add any attribute or function on your ModelAdmin and add it to your list_display. If you want it in your admin detail view, you also need to add it to readonly_fields (since it's not actually a form field):

@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):

    fields = ("pk", "foo")
    list_display = (
        "pk",
        "foo",
    )
    readonly_fields = ("foo",)

    @admin.display(description=_("label"))
    def foo(self, obj):
        return "bar"

The above example will show a field called "label" with the value "bar" in your admin detail page. Note that this field is not part of your actual form, it's just shown in the admin. This also works if you have a custom form defined.

Upvotes: 0

rix
rix

Reputation: 10632

I'm not altogether sure exactly what you want here. But presumably, if the field value isn't to be changed in admin, I suppose you just want to display it there right?

In that case you can define a method in the model, say 'name_language()' and then show it via list_display:

list_display = ('field1', 'field2', 'name_language')

Upvotes: 1

Related Questions