0

I am using AJAX to refresh a table in my template by using dataTable. When I get the results from the AJAX call (json) I'm using 'columns' to set every row. In one of the rows, I want to create a Django URL to another view.

What I have tried so far doesn't seem to work

function refreshData(event_ref) {
    var table = $('#datatable').dataTable({
        'processing': true,
        'serverSide': false,
        'responsive': true,
        'destroy': true,
        'ajax': {   
            'type': "GET",
            'url': "{% url 'events:index' %}",
            'dataSrc': ""
        },
        'columns': [
            { "data": "pk", render: function (pk) { return '<input type="checkbox" id="check_' + pk + '" name="check_all">'} },
            { "data": "fields.date_time" },
            { "data": "pk", render: function (pk) { return "<a href='{% url 'events:event' " + pk + "%}'>Click me</a>" }} 
        ],
        'order': [[ 2, "desc" ]],
        'columnDefs': [ {
            'targets': [0, 8], // column index (start from 0)
            'orderable': false, // set orderable false for selected columns
        }],
        'scroller': {
            loadingIndicator: true
        }
    });
}

The problem is in the line

{ "data": "pk", render: function (pk) { return "<a href='{% url 'events:event' " + pk + "%}'>Click me</a>" }} 

and what I get is this, Reverse for 'event' with arguments '(' + pk + ',)' not found. 1 pattern(s) tried: ['events/event/(?P[0-9]+)/']

My urls.py file is this

url('event/(?P<event_id>[0-9]+)/', views.event, name='event'),

and my view.py is this

def index(request):

    latest_event_list = events.objects.order_by('-date_time')

    if request.is_ajax():
        json = serializers.serialize('json', latest_event_list)
        return HttpResponse(json, content_type='application/json')

    template = loader.get_template('events/index.html')

    context = {
        'app_name': "events",
        'page_name': "real-time",
        'latest_event_list': latest_event_list,
        'total_events': len(latest_event_list)
    }
    return HttpResponse(template.render(context, request))

def event(request, event_id):

    latest_event_list = events.objects.order_by('-date_time')[:5]
    template = loader.get_template('events/event.html')
    context = {
        'app_name': "events",
        'page_name': "archive",
        'latest_event_list': latest_event_list,
    }

    return HttpResponse(template.render(context, request))

How can I create a Django URL with a value from AJAX call?

2 Answers 2

1

First of all, passing arguments to the {% url %} template tag isn't done by appending a string, to get the url you want in a template, you do:

{% url 'events:event' event_id=pk %}

Second, any template tag you use in your HTML is interpreted in the back-end once by Django when the HTML page is rendered. That is, before it gets to the browser and javascript starts running (the front-end). So what you're doing makes no sense, because you want javascript to dynamically change the url in the button.

If you look at the source of your HTML in your browser you'll see there's no template tag.

So you have to construct the url in javascript. What you could do is create a javascript variable in your template that is "{% url 'events:event' event_id=1 %}" (which in the HTML file parsed by the browser would be events/event/1 and then using string manipulation replace the "1" with the value of pk.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, javascript is front end language, thank you for helping me
0

you catch the error because call tag when the pk is not defined, so you can fix it by using some base url and then replace pk by current value, for example:

{
  var base_url = "{% url 'events:event' 0 %}";
  var url = base_url.substring(0, base_url.lastIndexOf('/') +1 ) + pk;
  return "<a href='" + url + "'>Click me</a>" 
}

1 Comment

I would rather use replace instead of substring, your answer is correct though:

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.