有没有一种简单的方法可以在 Django 管理站点中创建链式动态下拉列表?

Is there a simple way to create Chained Dynamic Drop Down List in Django Admin Site?

此刻我正在创建一个项目来学习如何使用django。在这个项目中有三个模型:

而我想实现的是在选择分类后动态选择相应的子分类,从而能够添加商品。

这是我的代码:

models.py

"""Z"""
from django.db import models

class Category(models.Model):
    """Z"""
    category_name = models.CharField("Name", max_length=50)

    class Meta:
        ordering = ('pk',)
        verbose_name = "Category"
        verbose_name_plural = "Categories"

    def __str__(self):
        """Z"""
        return self.category_name

class Subcategory(models.Model):

    """Z"""
    subcategory_name = models.CharField("Name", max_length=50)
    subcategory_parent = models.ForeignKey(
        Category, verbose_name="Parent", on_delete=models.CASCADE)

    class Meta:
        ordering = ('pk',)
        verbose_name = "Subcategory"
        verbose_name_plural = "Subcategories"

    def __str__(self):
        return self.subcategory_name

class Product(models.Model):
    """Z"""
    category = models.ForeignKey(
        Category, verbose_name="Category", on_delete=models.SET_NULL, null=True)
    subcategory = models.ForeignKey(
        Subcategory, verbose_name="Subcategory", on_delete=models.SET_NULL, null=True)
        product_name = models.CharField("Name", max_length=50, unique=True)

    class Meta:
        ordering = ('pk',)
        verbose_name = "Product"
        verbose_name_plural = "Products"

    def __str__(self):
        """Z"""
        return self.product_name

admin.py

"""Z"""
from django.contrib import admin
from .models import Category, Subcategory, Product

class SubcategoryInline(admin.StackedInline):
    """Z"""
    model = Subcategory
    extra = 1

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """Z"""
    inlines = (SubcategoryInline,) 

@admin.register(Subcategory)
class SubcategoryAdmin(admin.ModelAdmin):
    """Z"""

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    """Z"""
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "subcategory":
            kwargs["queryset"] = Subcategory.objects.filter(subcategory_parent=request.category)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

这是我尝试使用它时显示的错误:

AttributeError at /admin/prototype/product/add/

'WSGIRequest' object has no attribute 'category'

Request Method:     GET
Request URL:    http://127.0.0.1:8000/admin/prototype/product/add/
Django Version:     2.0.9
Exception Type:     AttributeError
Exception Value:    

'WSGIRequest' object has no attribute 'category'

Exception Location:     C:\asp\pilgrim\prototype\admin.py in formfield_for_foreignkey, line 30
Python Executable:  C:\Program Files\Python37\python.exe
Python Version:     3.7.0
Python Path:    

['C:\asp\pilgrim',
 'C:\Program Files\Python37\python37.zip',
 'C:\Program Files\Python37\DLLs',
 'C:\Program Files\Python37\lib',
 'C:\Program Files\Python37',
 'C:\Users\lisandro\AppData\Roaming\Python\Python37\site-packages',
 'C:\Program Files\Python37\lib\site-packages']

Server time:    Tue, 1 Jan 2019 11:48:18 -0400

您想将过滤后的查询集传递给您在管理员中使用的自定义表单(或者在特定的 view/template 中,如果您试图在真实前端执行此操作)。在这里查看答案: