如何根据 Django 管理中的另一个 select 标签选项更改 select 标签选项?

How to change select tag options according to another select tag's option in Django admin?

我在 admin.py

中有这个
class BrandAdmin(admin.ModelAdmin):
    list_display = ('name','category','date')
    form = BrandAdminForm
    class Media:
        js = ('own.js',)

admin.site.register(Brand,BrandAdmin)

和models.py

class Category(models.Model):
    name = models.CharField(max_length=100)

class Subcategory(models.Model):
    name = models.CharField(max_length=100)
    category = models.Foreignkey(Category, on_delete=models.CASCADE)

class Brand(models.Model):
    name = models.CharField(max_length=100)
    category = models.Foreignkey(Category, on_delete=models.CASCADE)
    subcategory = models.Foreignkey(Subcategory, on_delete=models.CASCADE)
    date = models.DateTimeField()

那么我如何 select 根据类别划分品牌子类别?

...
import json
...

class BrandAdminForm(forms.ModelForm):
    ''' collecting subcategories and corvert it to json. for use in javascript code '''
    data = {}
    for cat in Category.objects.all():
        data[str(cat.id)]={}
    for sub in Subcategory.objects.all():
        data[str(sub.category.id)][str(sub.id)] = {
                'id': str(sub.id),
                'cat_id': str(sub.category.id),
                'name': str(sub.name)
        }
    data = json.dumps(data)
    ''' converted to json '''

    category = forms.ModelChoiceField(queryset=Category.objects.all(), 
    widget=forms.Select(attrs={'onchange':  'category = this.options[this.selectedIndex].value; var data = ' + data + ';(function(){ var select = document.getElementById("id_subcategory");  select.options.length=0; select.options[select.options.length] = new Option("----",""); for(let [key, value] of Object.entries(data[category.toString()])) { select.options[select.options.length] = new Option(value.ady,value.id); } })()'}));
    class Meta:
        model = Brand
        fields='__all__'


class BrandAdmin(admin.ModelAdmin):
    list_display = ('name','category','date')
    form = BrandAdminForm
    # class Media:
    #     js = ('own.js',)

admin.site.register(Brand,BrandAdmin)

只需复制粘贴此代码 所有你需要的 django-form 和一些 javascript 代码

widget = forms.Select(attrs={
    'onchange': 'category = this.options[this.selectedIndex].value;   #category on changed
     var data = ' + data + ';(function(){ 
     var select=document.getElementById("id_subcategory"); 
     select.options.length=0; 
     select.options[select.options.length] = new Option("----",""); 
     for(let [key, value] of Object.entries(data[category.toString()])) { 
        select.options[select.options.length] = new Option(value.ady,value.id); 

} })()'}));