2014-02-05 36 views
3

這個[示例] [1]在Flask中使用WTForms和SQLAlchemy設置表單並向表單工作添加QuerySelectField。我不使用flask.ext.sqlalchemy,我的代碼:SQLAlchemy/WTForms:爲QuerySelectField設置默認選定值

ContentForm = model_form(Content, base_class=Form) 
ContentForm.author = QuerySelectField('Author', get_label="name") 
myform = ContentForm(request.form, content) 
myform.author.query = query_get_all(Authors) 

現在我想設置QuerySelectField的選擇列表的的默認值。

試圖在QuerySelectField傳遞default kwarg和設置selected屬性。沒有工作。我錯過了明顯的東西嗎?有人可以幫忙嗎?

回答

4

您需要將default關鍵字參數設置爲你希望成爲默認的Authors實例:

# Hypothetically, let's say that the current user makes the most sense 
# This is just an example, for the sake of the thing 
user = Authors.get(current_user.id) 
ContentForm.author = QuerySelectField('Author', get_label='name', default=user) 

或者,您可以提供的情況下到外地實例:

# The author keyword will only be checked if 
# author is not in request.form or content 
myform = ContentForm(request.form, obj=content, author=user) 
+0

第一種方法沒有效果。第二個導致'類型錯誤:「ContentForm」對象不是callable'例外... – casual

+0

@casual - 對不起,第二個應該是爲myform'的'的實例 - 更新。 (至於第一,會發生什麼,如果你使用作者的'id' ...我不認爲* *它應該工作,看代碼,但不能傷害嘗試吧) –

+0

很奇怪,選擇框具有正確的默認值的唯一情況是'myform = ContentForm(request.form,author = user)'但當然所有其他表單域都是空的。這可能是Flask請求的問題嗎? – casual