Ignasi
Ignasi

Reputation: 631

Parse whole list in querydict dictionary in Django

I have a querydict which I pass to Django's template. This querydict may look like this:

<QueryDict: {u'VAR1': [u'val1', u'val2', u'val3'], u'VAR2': u'val4', u'VAR3': [u'val5'], u'VAR4': []}>

I would like to parse the whole list from the querydict into a Javascript variable, so it looks like this:

var trial = ['val1', 'val2', 'val3'] for key "VAR1"

or

var trial = ['val5'] for key "VAR3"

or

var trial = [] for key "VAR4"

depending on which is the original list on the dictionary

I have tried many options but I haven't succeeded, any help please?

Upvotes: 0

Views: 827

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

Don't pass the querydict directly to the template. Convert it to a JSON string instead:

data = json.dumps(dict(my_querydict))

(You need to convert it to dict first, to bypass the querydict's special handling of multi-value keys.)

Now your JS can access it in your template:

var data = {{ data|safe }};
var var1 = data.var1;

Upvotes: 2

Related Questions