tags:

views:

71

answers:

1

I am reading the source code of the Django application blog at git://github.com/nathanborror/django-basic-apps.git.

How do you read the following Django code?

{% tags_for_object object as tag_list %}

My attempt: Make the variable object of the type *tags_for_object* and rename the variable to *tag_list*.

The object apparently is based on the file blog/templates/inlines/default.html:

{% if object %}
  {{ object }}
{% else %}
  {% for object in object_list %}
    {{ object }}
  {% endfor %}
{% endif %}

What is the befefit of putting the logic to two-step procedure: run single object, else loop through a list of objects?

+4  A: 

It looks like tags_for_object is the template tag from the django-tagging application.

From the django-tagging documentation:

tags_for_object:

Retrieves a list of Tag objects associated with an object and stores them in a context variable.

Usage:

{% tags_for_object [object] as [varname] %}

Example:

{% tags_for_object foo_object as tag_list %}

You can then loop through the tag_list variable in the template to display the tags.

{% tags_for_object foo_object as tag_list %}

<ul>
{% for tag in tag_list %}
  <li>{{ tag }}</li>
{% endfor %}
</ul>


For the second part of your question, you understand the code correctly. If the variable object exists in the context (and doesn't evaluate to False), it is displayed. If it does not exist in the context (or if it evaluates to False), then the code loops through the objects in object_list, and displays them.

As for why you would want to do this, you would have to look at the code that uses inlines/default.html to work out what the designer had in mind.

Alasdair
... and it has nothing to to with the `blog/templates/inlines/default.html` part
Javier
So the 3rd-party module makes it easier to handle pieces of information such as "user_name" and "time" for a comment, for instance. It seems that these variables are called tags in Django. - I am not yet completely sure why you need such a plugin, since you could just put such pieces of information to a single list for the given question.
Masi
You've tagged this question `django`, `python`, `beginner`. In the `Post` model in blog/models.py, the line `tags = TagField()` allows you to tag blog posts in a similar way. I couldn't see `user_name` and `time` when I briefly looked at the code on github, so I'm not sure what they are for.
Alasdair
They are just random examples in my current code. They are not related to the given code.
Masi