Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django ModelForm基于同一表单中的另一个字段的动态查找_Python_Django_Dynamic_Django Forms - Fatal编程技术网

Python django ModelForm基于同一表单中的另一个字段的动态查找

Python django ModelForm基于同一表单中的另一个字段的动态查找,python,django,dynamic,django-forms,Python,Django,Dynamic,Django Forms,所以我有这些模型: class Employee(models.Model): ACTIVE = 'A' INACTIVE = 'I' TERMINATED = 'T' STATUS_OPTIONS = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (TERMINATED, 'Terminated'), ) number = models.CharFiel

所以我有这些模型:

class Employee(models.Model):
    ACTIVE = 'A'
    INACTIVE = 'I'
    TERMINATED = 'T'
    STATUS_OPTIONS = (
        (ACTIVE, 'Active'),
        (INACTIVE, 'Inactive'),
        (TERMINATED, 'Terminated'),
    )
    number = models.CharField(max_length=50, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    status = models.CharField(max_length=1, choices=STATUS_OPTIONS, default=ACTIVE)
    is_supervisor = models.BooleanField(default=False)
    supervisor = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='employee_supervisor')

class Receipt(models.Model):
    Supervisor = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_supervisor')
    Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='receipt_employee')
    amount = models.DecimalField(max_digits=6, decimal_places=2, blank=False, null=False)
    reimbursed_on = models.DateField(blank=True, null=True)
    receipt_copy = models.FileField(upload_to='receipt_uploads/', null=False, blank=False)
您将注意到,Receipt类双foreignkey是Employee类的键。作为一名员工,他也可以是一名主管

表格:

class ReceiptForm(forms.ModelForm):
    class Meta:
        model = Receipt
        fields = [
            'Supervisor',
            'Employee',
            'amount',
            'receipt_copy'
        ]
        widgets = {}

    def __init__(self, *args, **kwargs):
        super(ReceiptForm, self).__init__(*args, **kwargs)
        self.fields['Supervisor'].queryset = Employee.objects.filter(status='A', is_supervisor=True)
        self.fields['Employee'].queryset = Employee.objects.filter(status='A') # Dynamic Filter Me...
所以在我的Employees表数据中有一群员工,其中一些是主管。大多数员工都与另一名员工——主管——有关系

视图:

我正在寻找一种方法,当在表单中选择您的主管时,员工查询集将被动态筛选,以仅列出与该主管相关的员工

我是否需要在客户端JS/AJAX上执行此操作?我假设我需要调用某种GET或POST函数。我只是不确定在不向django提交表单的情况下,向表单传达更新信息的最佳方式


提前谢谢

我明白了,必须使用AJAX

$("#id_Supervisor").change(
    function () {
        var url = $("#receiptForm").attr("data-employees-url");
        var supervisorId = $(this).val();
        if (supervisorId === '') {
            $("#id_Employee").html("<option value=\"\" selected>---------</option>");
        } else {
            $.ajax(
                {
                    url: url,
                    data: {
                        'Supervisor': supervisorId
                    },
                    success: function (data) {
                        $("#id_Employee").html(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("Status: " + textStatus + "\nError: " + errorThrown);
                        $("#id_Employee").html(null);
                    }
                }
            );
        }
    }
);
$(“#id#U主管”)。更改(
函数(){
var url=$(“#接收表单”).attr(“数据员工url”);
var supervisorId=$(this.val();
如果(监管者ID==''){
$(“#id_Employee”).html(“-----------”;
}否则{
$.ajax(
{
url:url,
数据:{
“主管”:主管ID
},
成功:功能(数据){
$(“#id_Employee”).html(数据);
},
错误:函数(XMLHttpRequest、textStatus、errorshown){
警报(“状态:+textStatus+”\n错误:+errorshown);
$(“#id_Employee”).html(空);
}
}
);
}
}
);
这帮我弄明白了:

还得耍些别的把戏。但是很好

$("#id_Supervisor").change(
    function () {
        var url = $("#receiptForm").attr("data-employees-url");
        var supervisorId = $(this).val();
        if (supervisorId === '') {
            $("#id_Employee").html("<option value=\"\" selected>---------</option>");
        } else {
            $.ajax(
                {
                    url: url,
                    data: {
                        'Supervisor': supervisorId
                    },
                    success: function (data) {
                        $("#id_Employee").html(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("Status: " + textStatus + "\nError: " + errorThrown);
                        $("#id_Employee").html(null);
                    }
                }
            );
        }
    }
);