RajveerParikh
RajveerParikh

Reputation: 111

Return dictionary from AJAX call using Django

I am making an AJAX call and would like it to return a dictionary of objects. No matter how I try to return the data, it throws an exception. As far as I can tell, it can only be because the response data is not in JSON format.

Any help would be really appreciated

def populateSources(request):
    if request.is_ajax():
        try:
            org = Organization.objects.get(pk=int(request.GET.get('org_id')))
            std_source_columns = StandardizedSourceColumn.objects.all()
            std_sources = StandardizedSource.objects.all()

            # Standardized Tables API Client
            std_tables_api_client = standardizedtablescli.ApiClient()
            std_tables_api_client.host = os.environ.get('STANDARDIZED_ENDPOINT')
            std_tables_api = standardizedtablescli.StandardizedtablesApi(std_tables_api_client)

            org_std_sources = std_tables_api.get_standardized_tables_by_id(org.id)
            ready_tables = std_tables_api.get_ready_raw_tables(org.id)

            ready_table_mapping = dict()
            ready_table_names = []

            for table in ready_tables:
                ready_table_names.append(table)


            for key, value in org_std_sources.iteritems():
                curr_source = StandardizedSource.objects.filter(name=key)
                if len(value['standard_mappings']) == 0:
                    if key in ready_table_names:
                        ready_table_mapping[curr_source] = False
                else:
                    ready_table_mapping[curr_source] = True

            json_response = {}
            json_response['result'] = ready_table_mapping
            return HttpResponse(
                json.dumps(json_response),
                content_type="application/json"
            )
        except:
            return HttpResponse(
                json.dumps("error"),
                content_type="application/json"
            )

Upvotes: 0

Views: 1018

Answers (2)

RajveerParikh
RajveerParikh

Reputation: 111

Yes, thank you for the help! I needed to use a serializer because I was creating a dictionary of objects. Since the objects weren't being serialized properly, the json_response was not in the correct format and was throwing an error because of that.

Upvotes: 0

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

You can use serialization instead, Refer the django docs https://docs.djangoproject.com/en/1.10/topics/serialization/

Upvotes: 2

Related Questions