Django Admin autofill data from ForeignKey select

Viewed 2110

I'm looking for a way to autofill some fields in the admin, based on a selected field. I have a foreign key field in an Inline and want to show some data from the current selected object in the form in realtime.

A simplified version of my code to exemplify what I'm doing would be:

# models.py

class Product(models.Model):
    code = models.CharField(max_length=6, default=0)
    name = models.CharField(max_length=25, null=True, blank=True)


class Provider(models.Model):
    code = models.CharField(max_length=6, default=0)
    name = models.CharField(max_length=25, null=True, blank=True)
    address = models.CharField(max_length=25, null=True, blank=True)


class ProductProvider(models.Model):
    product = models.ForeignKey(Product)
    provider = models.ForeignKey(Provider)
    cost = models.DecimalField(max_digits=6, decimal_places=2, default=0)

And my admin class is as follows:

# admin.py

class ProductProviderInline(admin.TabularInline):
    model = ProductProvider
    fk_name = 'product'

    fields = ('provider', 'cost', 'provider_address')
    readonly_fields = ('provider_address',)
    extra = 1

    def provider_address(self, obj):
        return obj.provider.address


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    model = Product
    list_display = ('code', 'name')
    inlines = [ProductProviderInline]


@admin.register(Provider)
class ProviderAdmin(admin.ModelAdmin):
    model = Provider

In this example, once a Provider have been selected, I'd like to update the readonly field address without having to save the object just yet.

I've tried most of the "autocomplete" third-party applications, sadly for me, most of them focus on autocomplete Choice fields, and not autofilling forms based on a Choice.

I'm sure this would need some Javascript/Ajax. Is there any third-party app. that cover this use case? I case there isn't, any suggestion on how achieve this?

0 Answers
Related