How to calculate using some form field value and auto populate that calculated value in another django admin form?

Viewed 307

I want to auto populate the calculated value in rent_price of admin.py:

models.py

class Book(models.Model):  
    ...  
    mrp        = models.DecimalField(max_digits = 9, decimal_places = 2)  
    rent_price = models.DecimalField(max_digits = 9, decimal_places = 2)  
    ...  

admin.py

class BookAdmin(admin.ModelAdmin):  
    ...  
    prepopulated_fields = {'rent_price': ('calculated value based on mrp',),}  
    ...
3 Answers

Here is simple answer based on @Muhammad_Tahir answer:

in your admin define a function:

def get_discount_rate(self, obj=None):
    mrp = ((obj.rent_price/obj.mrp)*100)
    return mrp

then inside your admin registration class, add following function:

@admin.register(ModelToRegister)
class ModelToRegisterAdmin(admin.ModelAdmin):
    ...
    prepopulated_fields = {}

    def get_prepopulated_fields(self, request, obj=None):
        prepopulated_fields = self.prepopulated_fields
        if obj:
            prepopulated_fields.update({
                'mrp': get_discount_rate(obj=obj)
            })
        return prepopulated_fields
Related