如何根据 django admin 中的另一个选择字段限制选择字段选项 [英] How to limit choice field options based on another choice field in django admin

查看:38
本文介绍了如何根据 django admin 中的另一个选择字段限制选择字段选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

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

class Item(models.Model):
    name = models.CharField(max_length=40)
    category = models.ForeignKey(Category)

class Demo(models.Model):
    name = models.CharField(max_length=40)
    category = models.ForeignKey(Category)
    item = models.ForeignKey(Item)

在创建新Demo时的管理界面中,用户从下拉列表中选择类别后,我想限制项目"下拉列表中的选择数量.如果用户选择另一个类别,则项目选择应相应更新.我想在客户端上限制项目选择,甚至在它到达服务器上的表单验证之前.这是为了可用性,因为项目列表可能有 1000 多个,能够按类别缩小范围将有助于使其更易于管理.

In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable.

是否有django 方式"来做这件事,或者自定义 JavaScript 是这里唯一的选择吗?

Is there a "django-way" of doing it or is custom JavaScript the only option here?

推荐答案

这里有一些javascript(基于JQuery)在类别改变时改变item选项值:

Here is some javascript (JQuery based) to change the item option values when category changes:

<script charset="utf-8" type="text/javascript">
  $(function(){
    $("select#id_category").change(function(){
      $.getJSON("/items/",{id: $(this).val(), view: 'json'}, function(j) {
        var options = '<option value="">--------&nbsp;</option>';
        for (var i = 0; i < j.length; i++) {
          options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
        }
        $("#id_item").html(options);
        $("#id_item option:first").attr('selected', 'selected');
      })
      $("#id_category").attr('selected', 'selected');
    })
  })
</script>

您需要在提供有效项目的 JSON 列表的/items/URL 上调用视图.

You need a view to be called on the /items/ URL that supplies a JSON list of the valid items.

您可以使用 将其挂接到您的管理员中模型管理媒体定义.

这篇关于如何根据 django admin 中的另一个选择字段限制选择字段选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆