开发者

Problem comparing keys in Appengine/Python

I'm trying to create a relationship between "tables" with Appengine/Python. Imagine I have a "table" for items, and a table for colors. I save the color of an item by saving the color key as an atribute of the item.

That's working well, but this particular piece of code is not working:

<select id="colorKey" name="colorKey">
  {% for color in colors %}
    <option value="{{ color.key }}"{% if color.key = item.colorKey %} selected="selected"{% endif %}>
      {{ color.name }} - {{ item.colorKey }} - {{ color.key }}
    </option>
  {% endfor %}
</select>

Since the {{ item.colorKey }} and {{ color.key }} variables are actually the same chain of characters, I only can think in a problem w开发者_如何学编程ith the types.

{{ item.colorKey }} is a string for sure. But maybe {{ color.key }} is not?


Indeed. color.key probably refers to an instance of the Key class. {% ifequal %} tries to compare a string with a Key object and the condition is never met.

Django automatically casts this object into a string when you're using {{ color.key }} but you have to provide {% if equal %} with an actual string.

You can declare a new property in your Color class that returns the key as string and then use it with {% if equal %}

class Color(db.Model):  
    ...
    @property
    def keyasstring(self):
        return str(self.key())

Then in your Django template:

{% ifequal color.keyasstring item.colorKey %}


 {% if color.key = item.colorKey %}

One too few ==?


Django doesn't support arbitrary expressions in 'if' tags (or anything else for that matter). You need to use the 'ifequal' tag - see the docs for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜