Skip to main content
 首页 » 编程设计

python之如何在 Django 模板的 AJAX 请求中返回 Django 表单对象

2025年05月04日51zhengyun_ustc

我正在尝试通过 Ajax 调用从 Django 模板调用我的 View 。

我希望表单对象响应 View ,这样我就可以在 div 元素中通过 jquery 呈现此表单。

这可能吗?怎么办?

这是我尝试过的:

主页.html

function get_edit_form(button, id) 
  { 
        $.ajax({ 
            url: "/manage/licenses/{{mls_signup_code}}/{{agent_id}}/" + id + "/", 
            type: "get", 
            data: {id: id}, 
            success: function(response) { 
            console.log(response); 
            $("#formdiv").html({{ response.as_p }}); 
            } 
        }) 
  } 

View .py

elif request.method == "GET": 
        owned_license_id = request.GET.get('id', '') 
        form = OwnedLicenseForm(owned_license_id) 
        return form 

请您参考如下方法:

我明白你想做什么,但你不能以这种方式呈现 html 表单:

$("#formdiv").html({{ response.as_p }}); 

我认为您混淆了服务器端渲染(Django 模板)和客户端渲染。服务器端呈现发生在您的服务器正在处理请求时,它无法呈现由在浏览器中运行的 javascript 生成的对象。

因为response是一个javascript对象,是jquery向你的url发送Ajax请求得到的。此时页面已经被Django的模板引擎渲染好,并发送到浏览器。 Django 模板甚至无法知道此响应。

我知道您想使用 as_p() 方法来呈现表单,您可以这样做:

function get_edit_form(button, id) 
{ 
        $.ajax({ 
            url: "/manage/licenses/{{mls_signup_code}}/{{agent_id}}/" + id + "/", 
            type: "get", 
            data: {id: id}, 
            success: function(response) { 
              console.log(response); 
              // response is form in html format 
              $("#formdiv").html(response); 
            } 
        }) 
  } 
 
# Views.py 
elif request.method == "GET": 
        owned_license_id = request.GET.get('id', '') 
        form = OwnedLicenseForm(owned_license_id) 
        return HttpResponse(form.as_p()) # return a html str