Generating a django HTML URL from a javascript function

Viewed 1555

I am using Django 1.10.6 and trying to generate a url from a javascript function in datatables

under url.py I have an page called profile setup like:

app_name = 'myapp'

urlpatterns = [
    url(r'^profile/(?P<pk>[0-9]+)/$', views.ProfileView.as_view(), name='profile'),
]

In javascript I have a django query send data to a variable and the data is displayed on a table with name and id fields:

var django_dat =[
    {
        "id": 1,
        "name":       "Jack Spicer",
    },
    {
        "id":2,
        "name":       "Ted Cracker",
    }
    {
        "id":3,
        "name":       "Justin Rollin",
    }
    {
        "id":4,
        "name":       "Boaty Boat",
    }
];

$(document).ready(function() {
    var table = $('#dattable').DataTable({
        data: django_dat,
        columns: [{
          'data': null,
          'render': function(data, type, row, meta)  {
            //Django URL
            return '<a href={% url 'myapp:profile' 2 %}>' + data.name + '</a>';}},
             {
          data: 'id'
        }]
    });
});

I am trying to change the URL so it link the name to a url like {% url 'myapp:profile' data.id %}. The above code is hardcoded to id=2 and works.

Tried changing it to:

return '<a href={% url 'myapp:profile' '+ data.id+ ' %}>' + data.name + '</a>' 

But that gave an No Reverse match error Reverse for 'profile' with arguments '('+ data.id+ ',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['profile/(?P<pk>[0-9]+)/$']

Also tried using the replace function:

return '<a href={% url 'myapp:profile' uid %}>'.replace('uid', data.id) +  data.name + '</a>'

but got the same error

3 Answers
Related