brewerja
brewerja

Reputation: 83

Django Admin: Dynamic Auto-Fill a Form Field from Selected Foreign Key's Attributes

I've got two simple models that are relevant to the question:

class CarMake(models.Model):
    make = models.CharField(max_length=64)
    default_cost = models.DecimalField(max_digits=7, decimal_places=2)

class Car(models.Model):
    model = models.CharField(max_length=64)
    make = models.ForeignKey(CarMake)
    cost = models.DecimalField(max_digits=7, decimal_places=2)

When creating or updating a Car object in the Django Admin, I'd like the cost field to be auto-populated with the default_cost of the chosen CarMake that is selected from the drop-down.

Currently, I am storing the cost as the make's default_cost if the field is left blank on saving the object. I'd prefer to do this dynamically when the make drop down chooses a value. I assume that the solution would involve some amount of JavaScript...

Upvotes: 1

Views: 1617

Answers (1)

scytale
scytale

Reputation: 12641

Yes, if you want the selection to be updated dynamically you'd have to use JS. Doing this kind of stuff would involve hacking the django admin site. You may be able to get away with just customizing the template to load some JS with and event handler that updates the specific drop-down. However this would be vulnerable to breakage when updating Django (the admin site templates have no guarantee of backwards compatibility). Personally I'd just write a custom view.

Upvotes: 2

Related Questions