Cijo
Cijo

Reputation: 2866

How to avoid hard-coding URLS in the static files on Django?

Is there any techniques to avoid hard coding URLs, especially the URLs for Ajax calls in an external static resource file like JavaScript files in Django.

Upvotes: 0

Views: 291

Answers (2)

schillingt
schillingt

Reputation: 13731

Another way of handling this is to add the URLs to data attributes on a container.

<div data-add-book-url="{% url "book:add" %}">
    ...
</div>

Then you pull that URL from that data attribute and use it in the AJAX call.

Upvotes: 2

zaidfazil
zaidfazil

Reputation: 9235

I don't know if there is any standard way to avoid hardcoding the URLs in the JavaScript files, but I could suggest a method. You could define an object in a separate file, something like "constants.js" in a format,

var api = {
    api_name1 : "url_ for your api1",
    api_name2 : "url_ for your api2",
    };

And remember to invoke the file before any other js files using the script tags. Then, the JavaScript will put this object "api" to the top of the declarations, due to the variable hoisting in JavaScript. Also, you could access each URL by calling api.api_name1. In case, if there is a change in the URLs, you only need to change in this file "constants.js".

This is a method I'm following inorder to avoid hardcoding the URLs myself. You could follow this or if you find another one which is better or efficient than this, please let me know.

Upvotes: 1

Related Questions