0

How can I pass a js variable to Django?

I have this simple code:

$(".update_btn").click(function() {
 var row_id=$(this).attr("row_id")

I want to pass row_id as index to a Django parameter called ticket_row, so that I could have ticket_row[row_id][1] I started to pass the first index with

console.log("{{ ticket_row['" + row_id + "'] }}") 

but it's working correctly. So, I need some help here :)

Any one has any suggestion / solution?

Thanks!

1
  • Are you wanting to send this in a form, or some other way? Commented Sep 23, 2017 at 1:44

1 Answer 1

1

You may want to use AJAX to send a request to the server. Or you could redirect the user to the page with an additional GET parameter: /path/to/page.html?row_id=2, replacing 2 with the ID you receive in JavaScript. Then access it via the request in your view:

def index(request):
    . . .
    row_id = 0
    if "row_id" in request.GET:
        row_id = int(request.GET["row_id"])
    try:
        selected_row = ticket_row[row_id]
    except IndexError:
        selected_row = ticket_row[0]
    return render(request, self.template_name, {"selected_row": selected_row})

In your template, you would then use:

console.log("{{ selected_row }}")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.