簡體   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