Given a Django template variable with a many-to-many model, is it possible to pass that to a Javascript function, and access it?
(What I’m trying to get, is a list of the groups, including pk, that the current user belongs to).
For example, if I have a user jsmith that belongs to two groups, alpha and beta:
<html>
<script type="text/javascript">
mangle_data("{{ user.name }}", "{{ user.groups }}", "{{ user.groups.all }"");
</script>
</html>
function mangle_data(username, groups, all) {
alert("username = " + username); // works. output = "jsmith"
alert("user.groups = " + groups); // output = "django.db.models.fields.related.ManyRelatedManager object"
alert("all = " + all); // output = "[Group alpha; Group beta;]"
}
In all cases, the parameter passed to Javascript, is a single flattened string. Ideally, I’d get an object, or even a list that contained both group names, and group pk.
Granted, I could find the pk of a group, given its name – but that’s a lot more steps. If I can get the data from the Django template directly into Javascript, it would be much cleaner.
How I wound up solving this, was to use a Context Processor to format the data, and pass it to a template variable: