i have 3 Models: Category
, SubCategory
and Product
.
SubCategory
is related to Category
with a Foreignkey
, and Product
is related to Category
and Subcategory
through a ForeignKey
.
What My Db looks like:
Category: Kids
-->SubCategory: Beanies
Category: Men
-->SubCategory: Hoodies
Now, When i want to add a Product and i select Kids
, in the Product
admin page, i only want related subcategories to show.
What I have tried:
using
formfield_for_foreignkey
but i can't seem to grasp how it works.I came across this question Django Admin Show / Hide Fields If Specific Value Is Selected In A Dropdown but i think that it's more field related than value related.
Suggestions I have found online:
- use ajax to fetch the subcategories and plug them in the child field.
My models:
class Category(models.Model):
name = models.CharField(max_length=250, db_index=True, unique=True)
slug = models.SlugField(max_length=250, db_index=True, unique=True)
class SubCategory(models.Model):
parent = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=250, db_index=True)
slug = models.SlugField(max_length=250, db_index=True)
class Product(models.Model):
parent = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category")
child = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
name = models.CharField(max_length=250, unique=True, db_index=True)
slug = models.SlugField(max_length=250, unique=True, db_index=True)
My Admin Models:
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = [
'name', 'slug'
]
@admin.register(SubCategory)
class SubCategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('name',)}
list_display = [
'name', 'slug', 'parent',
]
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = [
'name', 'slug', 'child',
]
prepopulated_fields = {'slug':('name',)}
list_per_page = 20
class Media:
js = ('javascript/hide_child_if_parent_is_none.js', )