dajax - very simple Ajax URL discovery for Django
Installation
Install with pip:
pip install dajax
Configuration
Add dajax
to settings.INSTALLED_APPS
:
INSTALLED_APPS = [
# ...
'dajax',
]
Add the following line to the end of your urlpatterns
list:
url(r'^dajax/', include('dajax.urls'))
In your HTML templates, add the JavaScript:
<script src="{% static 'dajax/js/jquery.dajax.js' %}"></script>
Usage
jQuery function signature
$.dajax(http_method, discovery_url, params, data, success, dataType)
-
http_method
can be GET or POST -
discovery_url
should be generated by Django with the following template code:{% url 'dajax:get_url' 'url_name' %}
whereurl_name
should be the name of the required URL pattern -
params
can be empty and should be a dictionary containing additional keyword arguments for URL resolution. -
data
,success
,dataType
are function arguments that are directly passed to$.get
or$.post
, refer to jQuery's documentation.
Example
Let's say you want to send an HTTP POST request to a view named candy_delete
that expects one argument, candy_pk
:
$.dajax('post', "{% url 'dajax:get_url' 'candy_delete' %}", {'candy_pk': candy_pk}, function(data) {
// handle data in case of success
}).fail(function(data) {
// this will be called if the URL resolution or the POST request fails
});
Configuration
There are two settings:
-
DAJAX_CACHE_AGE
: browser cache duration for URL requests, in seconds. Default value: 3600 (1 hour). -
DAJAX_URL_NAME_PREFIX
: automatically prefixes each URL name you pass. Empty by default.