【问题标题】:Django render template in template using AJAXDjango 在模板中使用 AJAX 渲染模板
【发布时间】:2018-11-25 12:57:18
【问题描述】:

我的网站目前在自己的页面上呈现表单。我现在正试图让它们在我的主页上的侧边栏 div 标签内呈现。但是,我不知道如何塑造 JavaScript 和/或视图,因此我将表单模板的 HTML 取回并插入到 div 标记中。

更新

我在控制台中收到以下错误:GET http://127.0.0.1:8000/new_trend/ 500 (Internal Server Error)

HTML(我想将表单模板注入到的主页上的标记):

<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})

【问题讨论】:

  • 你应该解释一下它目前的作用。你有任何错误或错误行为吗?
  • 是的,我意识到这一点并回来更新。我不知道如何调试终端,否则我会尝试发布更多详细信息。

标签: javascript django django-forms


【解决方案1】:

我能够自己解决这个问题。对于遇到此问题的其他人(包括我自己!),这就是我的工作方式。

JavaScript

这里有几个修复。首先你需要包含 csrftoken,你可以通过另一个 JS 函数来获取它。其次,AJAX 请求需要是 POST,而不是 GET(不知道为什么,如果您知道请在下方评论)。这是更新后的代码 sn-p...

// 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
    });
});

查看

需要纠正的第二件事是视图功能。首先,您需要将 HTML 呈现为字符串,然后在 HttpResponse 中返回该字符串。 This blog post 详细解释了原因,所以我不打算在这里讨论。这就是新代码的样子……

@login_required
def ajax_indicator_form(request):
    form = IndicatorForm()
    html = render_to_string('mysite/sidebar_trend.html', {'form': form})
    return HttpResponse(html)

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 2015-06-23
    • 2018-11-30
    • 2022-07-22
    • 1970-01-01
    • 2018-05-20
    • 2018-11-05
    • 2011-09-28
    • 2020-08-10
    相关资源
    最近更新 更多