0

I am currently using Django framework.

I would like to get the value of a javascript value wrote in an html file. I would like to be able to display it in my view file

Here is my html file from the folder templates:

<script>
var toto = "javascript";
document.write(toto)

</script>

This is my view file:

def javascript(request):
    # print the javascript value here
    return render(request, "rh/javascript.html")

Thank you for your help !

Victor
  • 21
  • 9

1 Answers1

0

You have to consider that your script runs on the client-site whereas the view function runs on the server-side. This is one main challenge when it comes to shifting variables from one end to the other.

To make a long story short:

You will have to make a http request from the client-site (for example using jQuery AJAX) to call the view. Then you can pass the variable via AJAX to the view function and use it for further logic.

Example:

your.html

<script type="text/javascript">
      // A CSRF token is required when making post requests in Django
      // To be used for making AJAX requests in script.js
      window.CSRF_TOKEN = "{{ csrf_token }}";
</script>

<div id="variable">Variable</div>

javascript

(function($) {

// trigger the logic on click of the container
  $('#variable').on('click', function() {

    // assign variable
    var variable_for_view = $(this).html();

    // make http request using AJAX
    $.ajax({
      type: 'post',
      url: '/your_url/', // this is the mapping between the url and view
      data: {
        'variable': variable, // ! here is the magic, your variable gets transmitted to the server
        'csrfmiddlewaretoken': window.CSRF_TOKEN
      },
      success: function(data) {
        print(sliced_variable)
      },
    });
  });
}(jQuery));

views.py

def your_view(request):

    # Assign variable from AJAX request
    variable = request.POST.get('variable')
    print(variable)

   variable.slice(3)    

    context = {
        'sliced_variable': variable
    }    

return render(request, 'your.html', context)
JSRB
  • 2,492
  • 1
  • 17
  • 48