简体   繁体   English

在 django 模型属性上传递 url 参数

[英]Passing url parameter on django modelform attributes

I need to create a form with 5 select fields, each one dependent of the previous one (Schools, Disciplines, Macro-Content, Micro-Content, Teacher)我需要创建一个包含 5 个 select 字段的表单,每个字段都依赖于前一个字段(学校、学科、宏观内容、微内容、教师)

I'm able to get only one working, passing an Ajax view to the form div:我只能让一个工作,将 Ajax 视图传递给表单 div:

  <form action="" id="orderForm" method="POST" discipline-queries-url="{% url 'ajax-load-discipline' %}>

and

<script src="//code.jquery.com/jquery-3.6.0.js"></script>
  <script>
    $("#institute").change(function () {
        const url = $("#orderForm").attr("discipline-queries-url");
        const instituteId = $(this).val();

        $.ajax({
            url: url,
            data: {
                'institute_id': instituteId
            },
            success: function (data) { 
                $("#discipline").html(data);
            }
        });

    });
</script>

From what I understand I'd need 4 different ajax views, one for each database query, and pass the url attribute through modelform attributes like this:据我了解,我需要 4 个不同的 ajax 视图,每个数据库查询一个,并通过如下 modelform 属性传递 url 属性:

            'discipline': forms.Select(attrs={'id': 'discipline', 'class': 'form-control',
                                              'discipline-queries-url': '{% url "ajax-load-discipline" %}'}),

But the special characters are escaping and returning something like this:但特殊字符是 escaping 并返回如下内容:

"GET /order/create/%7B%%20url%20%22ajax-load-discipline%22%20%%7D?institute_id=1 HTTP/1.1" 404 13568

So it is passing {% url "ajax-load-discipline" %} to the url...所以它将 {% url "ajax-load-discipline" %} 传递给 url ...

Any idea of what I can do to pass the correct parameters?知道我可以做些什么来传递正确的参数吗?

When you set attributes for a widget, it does not get rendered as if it were part of the template, it gets rendered as if it were a variable being rendered in the template, hence instead of "{% url 'ajax-load-discipline' %}" you should be writing the url itself there using reverse_lazy [Django docs] :当您为小部件设置属性时,它不会像模板的一部分一样呈现,它会像模板中呈现的变量一样呈现,因此不是"{% url 'ajax-load-discipline' %}"你应该在那里使用reverse_lazy [Django docs]编写 url 本身:

from django.urls import reverse_lazy


'discipline': forms.Select(attrs={'id': 'discipline', 'class': 'form-control', 'discipline-queries-url': reverse_lazy('ajax-load-discipline')}),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM