Accessing couchdb's UUID in django templates
I am kinda new to Couchdb and Django and was trying to extend the default sample (greetings) provided with couchdbkit. while making a basic CRUD example using the existing example, I wasn't able to access the couchdb's document id in the django template
When I run something like this
greetings = Greeting.view('greeting/all', descending=False)
for g in greetings:
print g._id
It prints fine, although when passed it to the template using
return render("home.html", {
"form": form,
"greet": greet,
"greetings": greetings
}, context_instance=RequestContext(request))
Using the similar loop as mentioned above I can access
{% for g in greetings %}
<tr>
<td>{{ g.date|timesince }} </td>
<td>{{ g.author }} </td>
<td>{{ g.content }}</td>
&l开发者_如何学Got;/tr>
{% endfor %}
The author and content, but when I introduced {{ g._id }}
I get an error TemplateSyntaxError at / Variables and attributes may not begin with underscores: 'g._id'
can somebody please explain how do i access the unique couchdb's id in django templates, since I know I can access the "_id" in view.py it isn't a problem with couchdbkit, the concern is a work around probably in view.py to maybe convert _id to id or something.
As mentioned, I am a newbie to django, hence maybe the question might be a little silly in itself.
PS: I am using coucdb 1.0.2, django 1.3.0 and python 2.6
Thanks.
Another option is accessing it using a templatetag
from django import template
register = template.Library()
@register.filter(name='get')
def get(d, k):
return getattr(d, k)
Then in your html code you can access it using:
{{object|get:"_id"}}
It saves storing more variables and you won't have to do it for each object you want to access it, which makes it DRYer.
The reason for the template error is simple: Django doesn't allow you to access attributes of objects that begin with a underscore. The reason for this is unknown to me, but by convention attributes that begin with an underscore are "private" in Python. So I guess this is enforced by Django to force the developers to don't do such things as their are bad style.
Frist, you should make sure, that there is no other way to access the id (like get_id()
or something). If not you can work around yout problem: Copy _id
to a new attribute for each greeting.
greetings = Greeting.view('greeting/all', descending=False)
for g in greetings:
setattr(g, 'couchId', g._id)
Now each instance in greetings has a new attribute couchID
where you can access the value of _id
. This work because Pythons dynamic nature allows you to modify anything at runtime - you can even create or remove attributes.
In your view you can simple do:
{% for g in greetings %}
<tr>
<td>{{ g.couchId }} </td>
<td>{{ g.date|timesince }} </td>
<td>{{ g.author }} </td>
<td>{{ g.content }}</td>
</tr>
{% endfor %}
精彩评论