[Answered ]-Getting Foreign Key data in Django Admin Add/Change Form

1๐Ÿ‘

i faced the same issue, in my case i use raw_id_field for my foreign keys and many to many fields in ModelAdmin And override add and change template.

you can use raw_id_field for forign keys and in your templates write javascript to change href of search icon for Pet foreign key field when Customer id field changed, and in href use url lookup to show only Pet which belongs to selected Customer

# stock/models.py

class Category(models.Model):
    title = models.CharField(max_length=255, blank=True)
    is_active = models.BooleanField(default=True)


class Product(models.Model):

    category = models.ForeignKey(
        Category, on_delete=models.PROTECT, related_name="product"
    )

    feature_option = models.ManyToManyField("FeatureOption", blank=True, related_name="product")


class Feature(models.Model):
    title = models.CharField(max_length=255, blank=True)
    category = models.ManyToManyField(Category, blank=True, related_name="feature")


class FeatureOption(models.Model):
    title = models.CharField(max_length=255, blank=True)
    feature = models.ForeignKey(
        Feature, on_delete=models.CASCADE, related_name="feature_option"
    )


# stock/admin.py

class CategoryAdmin(admin.ModelAdmin):
    raw_id_fields = ['parent']


class ProductAdmin(admin.ModelAdmin):
    add_form_template = 'admin/product_add_form.html'
    change_form_template = 'admin/product_change_form.html'
    raw_id_fields = ['category', "feature_option"]


class FeatureOptionAdmin(admin.ModelAdmin):
    list_filter = (("feature__category", admin.RelatedOnlyFieldListFilter),)

and in my template i use javascript to change the href of FeatureOption search icon for url lookup

<!-- product_add_form.html -->

{% extends "admin/change_form.html" %}
{% load i18n %}


{% block admin_change_form_document_ready %} {{ block.super }}
    <script lang="text/javascript">
        function changeFeatureOptionPopupUrl() {
            const featureOptionBaseUrl = "/admin/stock/featureoption/";
            let categoryTextBox = document.getElementById("id_category");
            document.getElementById("lookup_id_feature_option").href = featureOptionBaseUrl + "?feature__category__id__exact=" + categoryTextBox.value;
        }
        document.getElementById("lookup_id_feature_option").onfocus = function () {changeFeatureOptionPopupUrl()}
    </script>
{% endblock %}
๐Ÿ‘คAmin Basiri

Leave a comment