0

I am developing a project using django. I am using python dictionary to display data in for loop. I have set a dynamic key as per my requirement in dictionary using following code.

abc = {}

for user in users
 abc[user] = "some dynamic data"

context = {
            'contributors ': abc
        }
return render(request, 'contacts.html', context)

I send above code to my template to display data for each user.

{% for contributor in contributors %}

    {% for contributor_mp in contributor %}
        {{  contributor_mp }}
    {% endfor %}


{% endfor %}

I could not even access my code in view as I got error when I tried to serialize my dictionary

error:'long' object has no attribute '_meta'

I was using below to display my abc dictionary :

json_data = serializers.serialize("json", abc,use_natural_foreign_keys=True)
return HttpResponse(json_data)

So I used json_data = serializers.serialize("json", abc[123],use_natural_foreign_keys=True) return HttpResponse(json_data)

and got something like below (a validated json):

[{
    "fields": {
        "status": 0,
        "description": "Fresh & Healthy",
        "name": "Fresh & Healthy",
        "public": false,
        "custom_type": null,
        "user": "mpowner",
        "image_url": 
        "course_type": 1,
        "type": 1
    },
    "model": "mealplan",
    "pk": 140
}, {
    "fields": {
        "status": 0,
        "description": "evening snacks",
        "name": "evening snacks",
        "public": false,
        "custom_type": "health and taste",
        "user": "mpowner",
        "image_url": 
        "course_type": 1,
        "type": 1
    },
    "model": "mealplan",
    "pk": 155
}]

Now my problem is when I send this to my template I get an

error:'long' object is not iterable

As this is my first project in python and I am basically a php developer I am feeling really uncomfortable facing these kind of errors.Please help solving this and suggest some other way to use something like array ( a multi dimensional one) in python.

1 Answer 1

4

To iterate a dict in django template you need to use items:

{% for contributor, dynamic_data in contributors.items %}
    {{ user }} {{ dynamic_data }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.