[Fixed]-Django: How to assign a template variable to a views variable?

1👍

keep in mind that when a user makes a request to your app the view is processed and then a template is generated with the JS code. So if you have data in your javascript code you want to use in the view you need to make a request GET or POST, depending on the case, so the view can get this value.

For example, you could use the following GET request http://yourURL/acceptUserRequest/&elementText=True

Then in your view:

    elementText = request.GET.get('elementText', '')

If you want to stay on the same page and use ajax as we discussed in the comments do something like this. It is a very simple example. You create a view in Django which will receive the request.

    def accept_notification(request):
        parameter = request.GET.get('parameter', '')
        ... Do somehting with the data...

You may send more than one parameter as you wish.
You need a url for this view and you should attach a listener to the element in your HTML. Something like this.

    $("radiobutton").click(function(){
        $.get("http://www.your-url/accept_notification/&parameter=HELLO", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });

The alert is actually the callback function. In your case you can leave it blank or add a piece of code to execute after the server responds.

Leave a comment