accessing dictionry values in templates

5 views
Skip to first unread message

valler

unread,
Oct 9, 2009, 2:51:24 AM10/9/09
to Django users
How can i use dictionary values in example below?

def index(request):
msg = Msg.objects.all()
dict = {0:'good',1:'bad'}
return render_to_response('index.html',{'msg':msg,'dict':dict})


index.html

{% for m in msg %}
.......
{{m.status}} -> displays 0 or 1, I want to use my dict here
{{dict.m.status}} -> nothing, but
{{dict.0}} -> works
{{dict.1}} -> works
{% endfor %}

How can i use dictionary? Of course, i can write something like that:

{% for m in msg %}
.......
{% for key,val in dict.items %}
{% ifequal key m.status%} {{val}} {% endifequal %}
{% endfor %}
{% endfor %}

But i find this solution ugly. Is there any other way?
Thanks.

Bogdan I. Bursuc

unread,
Oct 9, 2009, 3:14:04 AM10/9/09
to django...@googlegroups.com
Why don't you set the value directly from the view functions ?

return render_to_response('index.html', {'val': dict[msg.status]})

valler

unread,
Oct 9, 2009, 3:28:24 AM10/9/09
to Django users
On Oct 9, 11:14 am, "Bogdan I. Bursuc" <bogdanbursu...@gmail.com>
wrote:
> Why don't you set the value directly from the view functions ?
>
> return render_to_response('index.html', {'val': dict[msg.status]})


I can not do this in view, because 'msg' is a queryset, returning many
values.
"" 'QuerySet' object has no attribute 'status' ""

Bogdan I. Bursuc

unread,
Oct 9, 2009, 3:37:59 AM10/9/09
to django...@googlegroups.com

I, see.

Don't know an alternative. Don't know if it's possible. You may consider
creating a tag or a filter for this job. That will result in a clean,
pretty solution.

Javier Guerra

unread,
Oct 9, 2009, 3:50:16 AM10/9/09
to django...@googlegroups.com, Bogdan I. Bursuc
Bogdan I. Bursuc wrote:
> You may consider
> creating a tag or a filter for this job.

or a function on the model class

--
Javier

Message has been deleted

valler

unread,
Oct 9, 2009, 4:15:04 AM10/9/09
to Django users
Thank you, this was the most beautiful solution.
I post it here, in case if someone will search it:

class Msg(models.Model):
......
......
......

status = models.IntegerField(choices=MSG_STATUS_LIST)
def getStatus(self):
return MSG_STATUS_LIST[self.status][1]

in template:

{{m.getStatus}}

Bogdan I. Bursuc

unread,
Oct 9, 2009, 4:19:49 AM10/9/09
to django...@googlegroups.com
It can be improved.

My suggestion is to use lower_underscored for methods names and you can
do something like this:
delete the method in your model because django models allready provides
a method for your choice fields:
get_field_display()
for your field would be:
get_status_display()

in your template you will have {{ m.get_status_display() }}

read more on this here:
http://docs.djangoproject.com/en/dev/ref/models/fields/#choices

At first i didn't knew status is a choices field.
Reply all
Reply to author
Forward
0 new messages