2011-06-30 73 views
0

我想爲我的模型中的單個字段創建編輯表單,其中textarea預填充該字段的當前值。但是,確切的字段名稱不是硬連線的,我希望它由url指定。Django訪問字段的值由關鍵字參數動態傳遞到模板

我的模型叫做Topic。兩個示例字段是Notes和Objectives。我可以硬線字段值,如下:

urls.py

(r'^/(?P<topicshortname>\d+)/(?P<whichcolumn>[^/]+)/edit/$', 'mysyte.myapp.views.edit_topic_text'), 

views.py

def edit_topic_text(topicshortname, whichcolumn): 
    thetopic = Topic.objects.get(topic__shortname__iexact = topicshortname) 
    content = Topic.objects.get(topic__shortname__iexact = topicshortname).objective 
    return render_to_response('topic_text_edit.html', locals()) 

topic_text_edit.html

​​

我也可以做通過使用{{ thetopic.objective }}在模板中硬連線,但如果我訪問了http://mysite.com/topic/Notes/edit/這些將預先填入客觀價值的形式,而不是票據價值。

我可以使用'whichcolumn'url參數指定在對象中更新哪個字段?

回答

0

您可以使用getattr按名稱獲取屬性的值。對於你的例子:

def edit_topic_text(topicshortname, whichcolumn): 
    thetopic = Topic.objects.get(topic__shortname__iexact = topicshortname) 
    content = getattr(thetopic, whichcolumn) 
    return render_to_response('topic_text_edit.html', locals()) 

但是,你應該也意識到了安全隱患的該的。用戶可以通過更改url來編輯他們喜歡的模型上的任何字段。 您應該做任何事情都要與該數據之前檢查whichcolumn的值,或限制URL配置的可能性,更具體的正則表達式,如:

(r'^/(?P<topicshortname>\d+)/(?P<whichcolumn>(Notes|Objectives))/edit/$', 'mysyte.myapp.views.edit_topic_text'), 

您也提到領域的「注意」和「目標「但在訪問現場‘客觀的’,所以你可能需要whichcolumn的值映射到字段名你有興趣,例如:

(r'^/(?P<topicshortname>\d+)/Objectives/edit/$', 'mysyte.myapp.views.edit_topic_text', {'whichcolumn': 'objective'}), 
(r'^/(?P<topicshortname>\d+)/Notes/edit/$', 'mysyte.myapp.views.edit_topic_text', {'whichcolumn': 'note'}), 

你應該知道的另一件事是,你在哪裏訪問通過調用兩次Topic.objects.get(...)兩次數據庫。你應該重用主題的價值。

+0

這對於預先填充textarea很有效。謝謝。我已經閱讀過,並嘗試去欺騙getattr(),但是沒有找到正確的語法。不幸的是,我的保存網址仍然不起作用 - 我努力將getattr()放入保存函數中,因爲它仍然被硬編碼爲'thetopic.objective = content'。感謝您的安全建議,我會實現這一點。評論還提到了訪問數據庫兩次,謝謝。 '目標'(複數)在我的文章中是一個錯字。 – nimasmi

+0

更新:用'setattr(object,field,value)'完成它,感謝http://stackoverflow.com/questions/763558/django-object-get-set-field – nimasmi

0

你應該注意的兩個概念和目標分隔在兩個不同的類,然後在你的主題主類使用它們作爲參考

這將是您更容易找回你的對象類型,並填寫正確的