[Django]-Get javascript variable's value in Django url template tag

97๐Ÿ‘

โœ…

I found a trick that might work under most circumstances:

var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString());

Itโ€™s clean, and it doesnโ€™t break DRY principle.

๐Ÿ‘คMike Lee

18๐Ÿ‘

Just making it clear so next readers can have a comprehensive solution. In regard to the question, this is how I used Mike Lee solution for an example case which is redirecting with Javascript to a new page with a parameter in a variable named tmp:

window.location = "{% url 'your_view_name' 1234 %}".replace(/1234/, tmp.toString());
๐Ÿ‘คOlfredos6

2๐Ÿ‘

one easy way to do this is

<div id="test" style="display: none;">
 {% url 'some_url:some_sub_url'%}
</div>


<script>
  url_mask = $( "#test" ).html()
</script>
๐Ÿ‘คMoayyad Yaghi

2๐Ÿ‘

var name = "{% url 'your_view_name' pk=0 %}".replace('0', name_variable);
๐Ÿ‘คVictor Tax

1๐Ÿ‘

Similar solution with concat instead of replace, so you avoid the id clash:

var pre_url = "{% url 'topology_json' %}";
var url = pre_url.concat(tool_pk, '/', graph_depth, '/');

But you need a non-parameter url to keep Django pleasant with the pre_url because the loading-time evaluation, my urls.py is:

urlpatterns = [
    url(r'^topology_json/$',
        views.topology_json,
        name='topology_json'),
    url(r'^topology_json/(?P<tool_id>[0-9]+)/(?P<depth>[0-9]+)/$',
        views.topology_json,
        name='topology_json'),
    ...
]

And parameters in view have suitable default values, so views.py:

def topology_json(request, tool_id=None, depth=1):                                             
    """                                                                                        
    JSON view returns the graph in JSON format.                
    """                                                                                        
    if tool_id:                                                                                
        tool = get_object_or_404(Tool, pk=tool_id)                                             
        topology = get_graph(str(tool), int(depth))                                            
    else:
        ...      

Django yet 1.11 here.

๐Ÿ‘คsantiagopim

0๐Ÿ‘

I donโ€™t think youโ€™ll be able to use a named argument to {% url %} from JavaScript, however you could do a positional argument or querystring parameter:

<script type="text/javascript">
    var tmp = window.location.hash, //for example
        url = {% url '[url_name]' %} + tmp + '/';
</script>

But, you could only do that once, when the template is initially rendered.

๐Ÿ‘คBrandon Taylor

Leave a comment