Django使用AJAX在模板中渲染模板 [英] Django render template in template using AJAX
问题描述
我的网站当前在其自己的页面上呈现表单.我正在尝试让它们现在在我的主页上的侧边栏div标签中呈现.但是,我不知道如何调整JavaScript和/或View的形状,因此我获取了表单模板的HTML并将其插入div标签.
My site currently renders forms on their own page. I'm trying to get them to render inside a sidebar div tag now on my main page. However, I can't figure out how to shape the JavaScript and/or View so I get the HTML of the form template back and inserted into the div tag.
更新
我在控制台中遇到以下错误: GET http://127.0.0.1:8000/new_trend/500(内部服务器错误)
I'm getting the following error in the console: GET http://127.0.0.1:8000/new_trend/ 500 (Internal Server Error)
HTML (要在其中插入表单模板的主页上的标签):
HTML (tag on the main page which I want to inject the form template into):
<div id="sidebar">
</div>
JavaScript
$(function() {
$("#new-trend").click(function(event){
alert("User wants to add new trend"); //this works
$.ajax({
type: "GET",
url:"/new_trend/",
success: function(data) {
$('#sidebar').html(data),
openNav()
}
})
});
});
查看
def new_indicator(request):
# if this is a POST request we need to process the form data
if request.method == "POST":
# create a form instance and populate it with data from the request:
form = IndicatorForm(request.POST)
# check whether it's valid:
if form.is_valid():
indicator = form.save(commit=False)
indicator.author = request.user
indicator.modified_date = timezone.now()
indicator.save()
return redirect('dashboard')
else:
form = IndicatorForm()
return render(request, 'mysite/sidebar_trend.html', {'form': form})
推荐答案
我能够自己弄清楚这一点.对于遇到此问题(包括我自己!)的其他人,这是我如何使其工作的方式.
I was able to figure this out on my own. For others who come across this (myself included!), here's how I got it working.
JavaScript
这里有几个修复程序.首先,您需要包含csrftoken,您可以通过另一个JS函数获得它.其次,AJAX请求必须是POST,而不是GET(不确定原因,如果您知道,请在下面发表评论).这是更新的代码段...
There was a couple of fixes here. First you need to include the csrftoken, which yo can get through another JS function. Second, the AJAX request needs to be a POST, not a GET (not sure why, if you know please comment below). Here's the updated code snippet...
// Get cookie for CSRF token (from Django documentation)
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
// Load new Trend form
$(function() {
$("#new-trend").click(function(event){
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "POST",
url: "/new_trend/",
data: {'csrfmiddlewaretoken': csrftoken},
success : function(data) {
$('#sidebar').html(data);
openNav()
}
})
alert("User wants to add new trend") //this works
});
});
查看
第二个需要更正的是View函数.首先,您需要将HTML渲染为字符串,然后在HttpResponse中返回该字符串.此博客文章详细说明了为什么,因此在这里我不再赘述.这就是新代码的样子……
The second thing that needs to be corrected is the View function. First you need to render the HTML into a string, then return the string in an HttpResponse. This blog post provides a detailed explanation of why so I'm not going to go into it here. This is what the new code looks like...
@login_required
def ajax_indicator_form(request):
form = IndicatorForm()
html = render_to_string('mysite/sidebar_trend.html', {'form': form})
return HttpResponse(html)
这篇关于Django使用AJAX在模板中渲染模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!