Aja*_*pta 1 python django django-templates
我正在尝试通过 Ajax 调用从 django 模板调用我的视图。
我想要表单对象作为视图的响应,以便我可以通过 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 }});
}
})
}
Run Code Online (Sandbox Code Playgroud)
视图.py
elif request.method == "GET":
owned_license_id = request.GET.get('id', '')
form = OwnedLicenseForm(owned_license_id)
return form
Run Code Online (Sandbox Code Playgroud)
我明白你在做什么,但你不能以这种方式呈现 html 表单:
$("#formdiv").html({{ response.as_p }});
Run Code Online (Sandbox Code Playgroud)
我认为您将服务器端渲染(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
Run Code Online (Sandbox Code Playgroud)
您可以结合使用 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)
Run Code Online (Sandbox Code Playgroud)
第 3 步:在 urls.py 中定义 AJAX url
[...
path(
'payment-method-ajax/<slug:method>/', # notice the slug in the URL
views.payment_method_ajax,
name='payment-method-ajax'),
...]
Run Code Online (Sandbox Code Playgroud)
第 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>
Run Code Online (Sandbox Code Playgroud)
form-fields 是加载动态表单的地方
<form id="id-form" style="display: none;">
{% csrf_token %}
<div id="form-fields"></div>
<input type="submit" value="Save Payment Details"/>
</form>
Run Code Online (Sandbox Code Playgroud)
确保将 slug 添加到主视图的上下文中
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 ****
}
Run Code Online (Sandbox Code Playgroud)
第 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5945 次 |
| 最近记录: |