繁体   English   中英

如何从Django模板的AJAX请求中返回django表单对象?

[英]How to return django form object in an AJAX request from django template?

我试图通过Ajax调用从Django模板中调用我的视图。

我希望表单对象能够响应视图,以便我可以通过div元素中的jquery呈现此表单。

可能吗 ? 怎么样?

这是我尝试的:

home.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 }});
            }
        })
  }

Views.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模板甚至无法知道此response

我了解您想使用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

您可以结合使用Django和JQuery来完成此任务。

第1步:创建一个非常简单的form_from_ajax.html模板

模板可以像{{form.as_p}}一样简单。 关键是不要继承您的基本模板。 您只是使用此form_from_ajax.html模板来呈现表单的HTML。

第2步:创建一个带有slug参数的视图,以帮助您获取正确的表单

def payment_method_ajax(request, method):  # method is your slug
    """Load a dynamic form based on the desired payment method"""

    options = {
        'ach': ECheckForm(),  # Dynamic form #1
        'credit-card': CreditCardForm(),  #  Dynamic form #2
    }

    if method in options.keys():
        context = {'form': options[method]}
    else:
        context = None

    template = 'your_app_name/form_from_ajax.html'
    return render(request, template, context)

步骤3:在urls.py中定义AJAX网址

[...
    path(
        'payment-method-ajax/<slug:method>/',  # notice the slug in the URL
        views.payment_method_ajax,
        name='payment-method-ajax'),
...]

第4步:更新您想要显示AJAX加载表单的模板

进行一些按钮以使用户选择适当的表单选项

<button id="btn_ach" onclick="load_payment_form(this)">ACH</button>
<button id="btn_credit_card" onclick="load_payment_form(this)">Credit Card</button>

form-fields是动态表单的加载位置

<form id="id-form" style="display: none;">
    {% csrf_token %}

    <div id="form-fields"></div>
    <input type="submit" value="Save Payment Details"/>
</form>

确保将子弹添加到主视图的上下文中

context = {
        'target': 'Add a New Payment Method',
        'h1': 'Add a New Payment Method',
        'ach': 'Save an ACH Profile',
        'credit_card': 'Save a Credit Card Profile',
        'slugs': ['ach', 'credit-card'],  # Here are the slugs ****
    }

步骤5:使用JQuery和按钮的onclick加载表单

<script>
    var ach = 'ACH';
    var creditCard = 'Credit Card';

    var form_urls ={
        ach : '{% url "payment-method-ajax" slugs.0 %}',
        creditCard : '{% url "payment-method-ajax" slugs.1 %}',
    }

    function load_payment_form(btn) {

        if(btn.innerText==ach) {
            get_url = form_urls['ach'];
            type = ach;
        }
        else if(btn.innerText==creditCard) {
            console.log('Load credit card form');
            get_url = form_urls['creditCard'];
            type = creditCard;
        }

        $.get({'url': get_url}).done(

               function(data) {
                document.getElementById('form-fields').innerHTML = data;})

        document.getElementById("id-form").style.display = "block";
    }
</script>

暂无
暂无

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

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