如何恢复字段的值以将其存储在变量中? Django管理表格

时间:2017-06-29 12:47:18

标签: jquery python json django

在我的Django Admin Form我有field看起来像这样:

当我按上面的others fields时,我想完成所有button

要做到这一点,我使用API给我一个JSON file

import requests

post_data = {'cdNom': value}
response = requests.post('https://example/json', data=post_data)
resp = response.json()[0]
print(resp)

此处未定义变量value但我想按下按钮将此值放入变量时恢复CDN_Name

我该怎么做?可以使用python,或者我必须在此jQuery中使用HTML button脚本?

如果我能做到这一点,那将会使我恢复一个特定的JSON file,之后我只需将每个key/value放在好的字段上?

1 个答案:

答案 0 :(得分:0)

你需要使用Ajax。

您在上面显示的脚本应该是Ajax脚本调用的视图。视图应该接受该值作为GET参数,并返回包含数据的JSON响应以填充其他字段。

因此,jQuery中的Ajax代码将是:

$('#my_button_name').getJSON({
  '{% url "populate_fields" %}',
  {value: $('#id_cdn_name').value()},
  function(data) {
    ... populate other fields with contents of data ...
  }
});

和Django代码将是:

def populate_fields(request):
    post_data = {'cdNom': request.GET('value')}
    response = requests.post('https://example/json', data=post_data)
    return HttpResponse(response.content)

和你的urls.py:

url(r'populate_fields', views.populate_fields, name='populate_fields'),