简体   繁体   中英

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM