Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding client side calculated fields to django admin

Say I've got a model like so:

class Spam(models.Model):
    a = models.IntegerField()
    b = models.IntegerField()

On the admin create/edit form. I want to add a non-editable field "c", that will contain the sum of whatever has been entered in a and b.

I have a boatload of ideas on how to accomplish this, and none of them sound very good.

Can anyone point me in the right direction?

like image 667
danatron Avatar asked Nov 29 '22 16:11

danatron


1 Answers

You can do it with ModelAdmin.readonly_fields

class SpamAdmin(admin.ModelAdmin):
    readonly_fields = ('get_c',)
    fields = ('a', 'b', 'get_c')

    def get_c(self, obj):
        return obj.a + obj.b
like image 102
Daniel Roseman Avatar answered Dec 07 '22 00:12

Daniel Roseman