Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django render template in template using AJAX

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})
like image 606
pheeper Avatar asked Oct 23 '25 18:10

pheeper


1 Answers

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)
like image 86
pheeper Avatar answered Oct 26 '25 07:10

pheeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!