admin中的另一个选择字段限制选择字段选项

admin中的另一个选择字段限制选择字段选项

本文介绍了如何根据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)

在创建新演示的管理界面中,用户从下拉列表中选择类别后,我会喜欢限制项目下拉菜单中的选择次数。如果用户选择另一个类别,则项目选择应相应更新。我想在客户端上限制项目选择,甚至在服务器上进行表单验证之前。这是为了可用性,因为项目列表可以是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的)来改变类别更改时的项目选项值:

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>

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

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

您可以使用。

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

07-28 05:10