简体   繁体   English

将数据从javascript传递到django admin

[英]pass data from javascript to django admin

I have two dropdown list say, "questions" and "choices" in django admin. 我在django admin中有两个下拉列表,分别是“ questions”和“ choices”。 Depending on the selected option in "question", options in "choices" will get populated. 根据“问题”中选择的选项,“选择”中的选项将被填充。 I wrote a javascript that gets triggered on question change, as shown below. 我编写了一个JavaScript,该JavaScript在问题更改时触发,如下所示。 To populate "choices", I need to query the database. 要填充“选择”,我需要查询数据库。 Can I do that from this javascript function? 我可以从此javascript函数中执行此操作吗? If yes, how? 如果是,怎么办?

Alternatively, if I could return the selected value to the ModelForm class in django admin, I could query database from there. 或者,如果我可以将所选值返回到django admin中的ModelForm类,则可以从那里查询数据库。 But I am unable to capture this return value in ModelForm and populate "choices" field after user selects an option in "questions". 但是当用户在“问题”中选择一个选项后,我无法在ModelForm中捕获此返回值并填充“选择”字段。 How do I do that? 我怎么做?

I could not find any answer on the internet. 我在互联网上找不到任何答案。 All I found was sending data from javascript to django views through HttpResponse. 我发现的只是通过HttpResponse将数据从javascript发送到django视图。 This approach also needs a separate regex definition in urls.py. 这种方法还需要在urls.py中有一个单独的正则表达式定义。 I cannot change the url while I communicate with javascript. 与JavaScript通信时,无法更改网址。

test.js test.js

function tryCustomiseForm() {
    choice=django.jQuery('[id$=choice_list]');
    var selection = null
    django.jQuery('[id$=question_list]').change(function() {
        selection = this.value;
    });
    return selection
}

(function($) {
   $(document).ready(function() {
      tryCustomiseForm();
   });
})(django.jQuery);

我最终使用django-smart-select在models.py中连接我的模型。

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

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