Question

I have a modelChoiceField created with Django:

lawsToValidate=forms.ModelChoiceField(queryset=LawsIdsModel.objects.filter(validated=0).values("releveAnnee", "releveMois", "noOrdre"), widget=forms.Select(attrs={'onchange': 'javascript: lawToValidateDisplay(this.value);'}))

The django code creates this html code:

<option value="{'releveMois': 1L, 'noOrdre': 2L, 'releveAnnee': 2009L}">{'releveMois': 1L, 'noOrdre': 2L, 'releveAnnee': 2009L}</option>

The django code calls my jquery function right after the click on the drop down list. If I display the selected value in my javascript function, here is what I have:

{'releveMois': 1L, 'noOrdre': 3L, 'releveAnnee': 2009L}

How do I get the information from this python dictionnary in jquery / javascript. How do I get releveMois, releveAnnee, noOrdre? If I try jQuery.parseJSON, it does not work!

EDIT: With the comments below, I understood that it was better to change the html output. Here is my template code to generate the drop down list:

<div id="lawsToValidateChoice" class="fieldWrapper">
            {{ form.lawsToValidate.errors }}
            <select  onchange="javascript: lawToValidateDisplay(this.value);" name="lawsToValidate" id="id_lawsToValidate">
                <option value="" selected="selected">Select a law to validate</option>
                {% for law in form.lawsToValidate.field.queryset %}
                    <option value="{{ law.releveAnnee }},{{ law.releveMois }},{{ law.noOrdre }}">releveAnnee={{ law.releveAnnee }}, releveMois={{ law.releveMois }}, noOrdre={{ law.noOrdre }}</option>
                {% endfor %}
            </select>
        </div>

No problem anymore to parse the values! Solved!

Was it helpful?

Solution 3

A better way to solve that... The problem is : when selecting a few columns with values in a queryset, it messes the output. The solution was to use only instead (before the filter).

lawsToValidate=forms.ModelChoiceField(queryset=LawsIdsModel.objects.only("releveAnnee", "releveMois", "noOrdre").filter(validated=0), widget=forms.Select(attrs={'onchange': 'javascript: lawToValidateDisplay(this.value);'}))

OTHER TIPS

You need to use the json module to serialize your results, not the str conversion of your dictionary.

return HttpResponse(json.dumps(result), mimetype="application/json")

Better still, use a JSONResponse() object or a Django serializer to create the JSON result for you; the first is a full replacement for the HttpResponse object that encodes to JSON, and ensures the correct mimetype is used.

First create a JSON at server side (e.g. using json module):

import json
json = json.dumps(queryset)

Then parse retrieved JSON in JavaScript with parseJSON() (or JSON.parse for modern browsers):

var json = $.parseJSON(jsonVar);
console.log(json.releveMois);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top