views:

21

answers:

1

Hello all,

tl:dr

How would a hosted django app correctly transform resource paths to match any hosted location (/ or /test or /testtest)?

Full Description

Let me try to explain what I am trying to do.

I am trying to write a somewhat re-usable django app which I intend to use from within multiple projects. This app is called systemstatus.

  • The systemstatus app provides a page under '$^' which provides a simple interface to query the system status.
  • This page makes an ajax query back to the systemstatus app to determine the actual system status and report it on the UI.
  • The systemstatus app provides a location '^service/$' which points to the ajax call handler.
  • This page has to somehow figure out the correct URI for the ajax handler depending on where this app is hosted (e.g. under / or /status or /blahblah).

I am wondering what an ideal way of doing this would be. I would say that this applies to other resources bundled inside the app too (stylesheets, images).

Right now I am using request.path to determine what the target path should be. This path is then passed down as a parameter to the template. But this approach will soon become too cumbersome to handle.


def system_status (request):
    queryPath = request.path + "service/"
    return render_to_response ('systemstatus.html', {'queryPath': queryPath})

My page template looks like this:


function do_ajax () {
    $.getJSON ('{{ queryPath }}', function (data) {
        $("#status").html (data.status);
    });
}

Thanks!

+2  A: 

You shouldn't hardcode your urls like that, but use reverse instead!

Django also has a built-in template tag to reverse urls. So you could do something like

function do_ajax () {
    $.getJSON ('{% url path.to.my_ajax_view %}', function (data) {
        $("#status").html (data.status);
    });
}

directly in your template!

You can also send the ajax request directly to your current page's url and check if it is an ajax request or not:

def my_view(request):
    if request.is_ajax():
        # generate response for your ajax script
    else:
        # generate the response for normal request
        # (render template of your page)
lazerscience
Oh sweet! This sounds perfect. I will give this a try and see if I can get this to work. Thanks for the handy tip as well. Is there a way to specify the url for the current view in the django template (the one that is processing the template), so that instead of saying {% url path.to.my_ajax_view %} I can just say something like {% current_view %} and the url of the current view is placed there. Or is it the same as using request.path?
verma
Worked like a charm! Thanks again!
verma
I do not see any disadvantage in using `request.path`! If anybody knows it better please tell me. Or use `{% url path.to.system_status_view %}`
lazerscience