When I write my JS files for a Django project, of course I do some AJAX calls, and for the moment the urls for those calls are hard-coded (which is very ugly).
I was thinking of having the JS files served by django (instead of Apache), so I could take advantage of the template tags ({% url %}
!!!).
Is there a reason why I shouldn't do this ?
Or is there a right way to do this ?
(I can give a least one : it will consume a lot of time resending JS files that haven't changed. What would be great is to have an application that generates files when restarting django server, and serves them statically after !)
Django is a server side web application framework. What this means is all the work is taking place on the server. The server receives a request and sends it to Django, which programmatically generates an HTML response. Javascript (including jQuery) is generally used on the client side.
It takes care of a lot of the hassle of Web development, letting you focus on writing your application without any need to reinvent the wheel. It's free, open source and fast. Additionally, the Django framework enables you to model your domain and code classes, and before you know it, you already have an ORM.
I searched deeper in those asset manager applications from djangopackages, have found out that django-mediagenerator provides that feature, even if it is not well documented : you can generate your js or css files as django templates, and then serve them statically (they are also bundled, and caching is managed etc ... so two birds with one stone + it is really easy to set-up !).
In order to have JS files generated as django templates (after having set-up django-mediagenerator
), just add the filter :
ROOT_MEDIA_FILTERS = {
'js': 'mediagenerator.filters.template.Template',
}
in your settings.
I would go for a hybrid technique. Serve most of your javascript statically. But in your Django template, have a <script>
block that defines various global variables, which are generated by the server-side code - url
is a good example. Then your static JS can refer to the variables that are generated in the dynamic code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With