Django render template in template using AJAX

别说谁变了你拦得住时间么 提交于 2021-02-08 02:19:09

问题


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.

UPDATE

I'm getting the following error in the console: GET http://127.0.0.1:8000/new_trend/ 500 (Internal Server Error)

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

VIEW

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

回答1:


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

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

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)


来源:https://stackoverflow.com/questions/50879653/django-render-template-in-template-using-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!