我正在編寫一個ToDo列表應(yīng)用程序,以幫助自己開始使用Python。該應(yīng)用程序在GAE上運行,我將待辦事項存儲在數(shù)據(jù)存儲區(qū)中。我想將每個人的物品展示給他們,也要單獨展示給他們。問題是該應(yīng)用程序當前向所有用戶顯示所有項目,因此我可以看到您寫的內(nèi)容,也可以看到我寫的內(nèi)容。我以為將我的todo.author對象轉(zhuǎn)換為字符串并查看它是否與用戶名匹配是一個不錯的開始,但是我不知道該怎么做。這就是我的main.py中的內(nèi)容... user = users.get_current_user()if user: nickname = user.nickname() todos = Todo.all() template_values = {'nickname':nickname, 'todos':todos}...def post(self): todo = Todo() todo.author = users.get_current_user() todo.item = self.request.get("item") todo.completed = False todo.put() self.redirect('/')在我的index.html中,本來是這樣的:<input type="text" name="item" class="form-prop" placeholder="What needs to be done?" required/>... <ul>{% for todo in todos %} <input type="checkbox"> {{todo.item}} <hr />{% endfor %}</ul>但我只想向創(chuàng)建它們的用戶顯示項目。我想嘗試{% for todo in todos %} {% ifequal todo.author nickname %} <input type="checkbox"> {{todo.item}} <hr /> {% endifequal %}{% endfor %}無濟于事。列表變成空白。我以為是因為todo.author不是字符串。我可以將值讀取為字符串,還是可以將對象轉(zhuǎn)換為String?謝謝!
3 回答

鴻蒙傳說
TA貢獻1865條經(jīng)驗 獲得超7個贊
在python中,該str()
方法類似于toString()
其他語言中的方法。稱為傳遞對象以將其轉(zhuǎn)換為字符串作為參數(shù)。在內(nèi)部,它調(diào)用__str__()
參數(shù)對象的方法以獲取其字符串表示形式。
但是,在這種情況下,您正在比較UserProperty
數(shù)據(jù)庫中的作者,該作者的類型users.User
與昵稱字符串相同。您將需要在模板中比較nickname
作者的屬性todo.author.nickname
。

桃花長相依
TA貢獻1860條經(jīng)驗 獲得超8個贊
在Python中,我們可以使用__str__()
方法。
我們可以像這樣在我們的類中重寫它:
class User: firstName = '' lastName = '' ... def __str__(self): return self.firstName + " " + self.lastName
并且在跑步時
print(user)
它將調(diào)用該函數(shù)__str__(self)
并打印firstName和lastName

千巷貓影
TA貢獻1829條經(jīng)驗 獲得超7個贊
str()
是等效的。
但是,您應(yīng)該過濾查詢。目前,您的查詢是all()
Todo。
todos = Todo.all().filter('author = ', users.get_current_user().nickname())
或者
todos = Todo.all().filter('author = ', users.get_current_user())
取決于您在Todo模型中定義的作者。AStringProperty
或UserProperty
。
注意nickname
是一種方法。您正在傳遞方法,而不是模板值中的結(jié)果。
添加回答
舉報
0/150
提交
取消